运行时错误:1004应用程序定义或对象定义的错误

时间:2017-06-21 19:44:10

标签: excel vba excel-vba

运行以下代码时出现运行时错误:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationAutomatic
Application.DisplayStatusBar = False
Application.EnableEvents = False

Dim c, OrgList, vtList, FndRng As Range
Dim Tbl As ListObject
Dim NewRow As ListRow
Dim Org, Track As Worksheet

Set Org = ActiveWorkbook.Worksheets("Org List")
Set Track = ActiveWorkbook.Worksheets("Visit Tracking Sheet")
Set Tbl = Track.ListObjects("TrackTbl")
Set OrgList = Org.Range(Cells(2, 1), Cells(Org.UsedRange.Rows.Count, 1))
Set vtList = Track.Range("TrackTbl[Org ID]")

一切都运行正常,直到我Set ChngList = Track.Range("TrackTbl[Org ID]")抛出Run-time Error: 1004。我也尝试了以下替换行,所有这些都抛出相同的错误:

  • Set vtList = Tbl.Range(Cells(2, 1), Cells(ListRows.Count, 1))
  • Set vtList = Track.Range(Cells(2, 1), Cells(Track.UsedRange.Rows.Count, 1))
  • Set vtList = Track.Tbl.Range(Cells(2, 1), Cells(ListRows.Count, 1))
  • Set vtList = Tbl.Range

我对此感到茫然,并且无法找到解决方案。我认为在表中设置Range引用单元格是一个问题,但我不确定。

1 个答案:

答案 0 :(得分:1)

感谢Siddharth Rout指出我正确的方向。

答案涉及两个我没有注意到的问题。第一个是错误实际发生在Set OrgList行而不是Set vtList行。导致错误是因为即使我引用了正确的工作表,没有With行,我也必须在该行的每个点引用该工作表。更正后的代码如下:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationAutomatic
Application.DisplayStatusBar = False
Application.EnableEvents = False

Dim c, OrgList, vtList, FndRng As Range
Dim Tbl As ListObject
Dim NewRow As ListRow
Dim Org, Track As Worksheet

Set Org = ActiveWorkbook.Worksheets("Org List")
Set Track = ActiveWorkbook.Worksheets("Visit Tracking Sheet")
Set Tbl = Track.ListObjects("TrackTbl")
Set OrgList = Org.Range(Org.Cells(2, 1), Org.Cells(Org.UsedRange.Rows.Count, 1))
Set vtList = Track.Range("TrackTbl[Org ID]")

我本可以使用With来消除为行中每个Range.Cells引用工作表的需要,但它的代码数量相同,工作表名称很短。无论哪种方式都适用于遇到此问题的任何人。