我正在尝试使用word中的vba来计算excel中列表的行数。问题是我似乎无法在通过vba打开的Excel驱动器上的Excel文件中使用exWb.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
函数。
我试图弄清楚我是否错误地打开了excel文件,但是我可以使用exWb.Sheets("Sheet1").Cells(1, 1)
从单个单元格中获取值
我的代码:
Private Sub B_FillForm_Click()
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
Set exWb = objExcel.Workbooks.Open("D:\DATA.xlsx")
Dim last_row As Long
last_row = exWb.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
MsgBox (last_row)
exWb.Close
Set exWb = Nothing
End Sub
我的excel文件当前已填充A1-A5。
我希望输出是显示5的消息框,但实际输出是显示以下错误消息:
“运行时错误424,需要对象”
答案 0 :(得分:-1)
您需要先声明工作簿对象,然后才能设置引用。
Private Sub B_FillForm_Click()
Dim objExcel As Object
Dim exWb As Workbook 'missing from your code
Set objExcel = CreateObject("Excel.Application")
Set exWb = objExcel.Workbooks.Open("D:\DATA.xlsx")
Dim last_row As Long
last_row = exWb.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
MsgBox (last_row)
exWb.Close
Set exWb = Nothing
End Sub