0

我正在尝试从 MS-Access VBA 计算 Excel 电子表格中非空单元格的数量。

这个想法是我在 MS-Access 中单击表单上的一个按钮,非空单元格的数量存储为字符串。

调用 Excel 工作簿文件,调用"MattExcelFile.xls"该工作簿中的工作表,"Sheet1"我想在其上使用 ExcelCOUNTA函数的范围是"C1:C500".

这是我到目前为止拼凑的代码:

Option Compare Database

Sub ImportDataFromRange()

Dim xlFilePath As String
Dim rowVariable As String

xlFilePath = "C:\Users\Matt\Desktop\MattExcelFile.xls"

rowVariable = Excel.Application.WorksheetFunction.CountA(Workbooks(xlFilePath).Sheets("Sheet1").Range("C1:C500"))

Debug.Print rowVariable

End Sub

Private Sub Command0_Click()

ImportDataFromRange

End Sub

这是我在运行此代码时收到的错误消息,突出显示该rowVariable = ...行:

运行时错误“9”:

下标超出范围

4

1 回答 1

2

我不确定您是否设置了适当的引用,因此这里是为您提供的完整代码,其中包含一些注释。

Sub test()
Dim rowVariable As String '<--why string?

'1st
Dim xlFilePath
    xlFilePath ="C:\Users\Matt\Desktop\MattExcelFile.xls"

'2nd- set refernces
Dim EXL As Object
Set EXL = CreateObject("Excel.Application")

'3rd open worksheet- required
With EXL
   .Workbooks.Open xlFilePath

'4th count using WF- set appropriate reference to workbook
'be careful about sheet name- give error '9'
    Dim tmpName() As String
    tmpName = Split(xlFilePath, "\")
    rowVariable = .WorksheetFunction.CountA(.Workbooks(tmpName(UBound(tmpName))).Sheets("Arkusz1").Range("A2:A10"))
'control of value
    Debug.Print rowVariable
End With

'5th-close everything and clean
EXL.Quit
Set EXL = Nothing
End Sub
于 2013-04-11T03:14:23.577 回答