2016-03-21 43 views
0

我想在打開excel工作簿後得到最後一行數據,但它返回「運行時錯誤1004:應用程序定義或對象定義的錯誤」我已經多次使用這種格式的代碼,所以我不知道我在這裏錯過了什麼。 我將變量定義爲Long,有沒有人有任何想法?我的代碼如下:VBA:運行LastRow代碼時出現應用程序定義的錯誤

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

什麼行不出錯後(高亮)調試器停止彈出的代碼中使用了兩次?總的來說,當VBA無法找到特定範圍時,我發現這個錯誤,因爲不同的工作簿恰好處於活動狀態,或者工作表名稱已更改。 –

+0

代碼停止在lastRow1 = wsMVPComm.Range(「A」&Rows.Count).End(xlUp).Row – MCJNY1992

+0

步驟通過您的代碼,並查看哪一行實際引發錯誤 – user3598756

回答

3

則很可能開始作爲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) 
相關問題