我正在尝试从MS-Access VBA计算Excel电子表格中的非空单元格数。
我的想法是单击MS-Access中表单上的按钮,非空单元格的数量将存储为字符串。
Excel工作簿文件名为"MattExcelFile.xls"
,该工作簿中的工作表名为"Sheet1"
,我想要使用Excel的COUNTA
函数的范围为"C1:C500"
。< / p>
这是我到目前为止拼凑的代码:
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':
下标超出范围
答案 0 :(得分: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