【问题标题】:VBA: Application-Defined Error when running LastRow CodeVBA:运行 LastRow 代码时出现应用程序定义的错误
【发布时间】: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

标签: vba excel


【解决方案1】:

您以 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多