运行LastRow代码时VBA:应用程序定义的错误
我想打开一个Excel工作簿后得到最后一行数据,但它返回“运行时错误1004:应用程序定义或对象定义的错误”我多次使用这种格式的代码,所以我不知道我在这里错过了什么。 我把variables定义为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
如果有人有任何想法,我会很感激! 谢谢。
最有可能的是你打开的工作簿是wsMVPComm
是旧的Excel格式,而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)