2017-06-21 123 views
1

我得到一個運行時錯誤,當我運行下面的代碼:運行時錯誤:1004應用程序定義或對象定義的錯誤

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

我在這個虧損一個並且很難​​找到解決方案。我認爲這是在表中設置範圍引用單元格的問題,但我不確定。

+0

代碼的其餘部分在哪裏?我沒有看到你在哪裏定義'ChngList' – dwirony

+1

請看看[this](https://stackoverflow.com/questions/36368220/is-the-in-range-necessary-when-defined-by-cells)的答案你的問題 –

+0

@dwirony對不起,這應該說'Set vtList',因爲它顯示在我發佈的代碼的最後一行。 –

回答

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,但它本來的碼相同的量和片材的名稱是短。無論哪種方式都應該適用於遇到這個問題的任何人。

相關問題