我打算在打开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
如果有人有任何想法,我真的很感激!谢谢。
答案 0 :(得分:3)
您打开的wsMVPComm
工作簿很可能是旧格式,而ThisWorkbook
是新格式
尝试
lastRow1 = wsMVPComm.Range("A" & wsMVPComm.Rows.Count).End(xlUp).Row
而不是
lastRow1 = wsMVPComm.Range("A" & Rows.Count).End(xlUp).Row
你可以使你的功能更通用,并帮助你避免如下的问题
Function get_ws_end_row(ws As Worksheet, column_with_data As Long) As Long
get_end_row = ws.Cells(ws.Rows.Count, column_with_data).End(xlUp).Row
End Function
然后你可以在发布的代码中使用它两次
endRow = get_ws_end_row(ws, 1)
...
lastRow1 = get_ws_end_row(wsMVPComm, 1)