【发布时间】:2016-03-21 13:49:23
【问题描述】:
我试图在打开 Excel 工作簿后获取最后一行数据,但它返回“运行时错误 1004:应用程序定义或对象定义的错误”我已经多次使用这种格式的代码,所以我我不确定我在这里缺少什么。 我将变量定义为 Long,有人有什么想法吗?我的代码如下:
Function get_end_row(ByVal column_with_data As Long) As Long
Dim last_row As Long
last_row = ThisWorkbook.Sheets(1).Rows.Count
get_end_row = ThisWorkbook.Sheets(1).Cells(last_row, column_with_data).End(xlUp).Row
End Function
Sub Master()
Call MVP
End Sub
Sub MVP()
Dim endRow As Long
Dim wb As Workbook, ws As Worksheet
Dim lastRow1 As Long
Set wb = ThisWorkbook
Set ws = ThisWorkbook.Sheets(1)
endRow = get_end_row(1)
Set mvpcomm = Workbooks.Open("File Path")
Set wsMVPComm = mvpcomm.Sheets("Combined")
lastRow1 = wsMVPComm.Range("A" & Rows.Count).End(xlUp).Row
wsMVPComm.Range("A2:AZ" & lastRow1).Copy Destination:=ws.Range("A" & endRow + 1)
End Sub
如果有人有任何想法,我将不胜感激!谢谢。
【问题讨论】:
-
错误弹出后调试器在哪一行停止(高亮)?通常,当 VBA 无法找到特定范围时,我会看到此错误,这可能是因为另一个工作簿恰好处于活动状态,或者工作表名称已更改。
-
代码停在 lastRow1 = wsMVPComm.Range("A" & Rows.Count).End(xlUp).Row
-
单步调试你的代码,看看哪一行实际抛出了错误
-
试试这个:
wsMVPComm.Range("A" & wsMVPComm.Rows.Count).End(xlUp).Row -
我怀疑您的工作簿格式不同。使用:
lastRow1 = wsMVPComm.Range("A" & wsMVPComm.Rows.Count).End(xlUp).Row