2017-02-16 27 views
-1

我正在使用VBA循環訪問參考號ROID列表,並從單獨的頁面返回正確的全名(ROIDA)。其中全名所在的頁面在列d參考號和列A全稱面向對象的錯誤 - 引用其他工作表?

Sub Main() 
'Set variable types 
    Dim WorksheetA As Excel.Worksheet 
    Dim WorksheetB As Excel.Worksheet 
    Dim ROID As Range, ROIDA As Range 

    Set WorksheetA = ActiveWorkbook.Sheets("WorksheetA") 
    Set WorksheetB = ActiveWorkbook.Sheets("Approval Flows") 

'Replacing ROID #s with full Name 
    'Define range of active requesting offices 
    Set ROID = WorksheetA.Range(Range("A7"), Range("A7").End(xlDown)) 

    'Define range of attention lines and associated ROIDs 
    Set ROIDA = WorksheetB.Range(Range("D7"), Range("D7").End(xlDown)) 

    'Loop through ROIDs and replace with ATTN line 
    For Each ID In ROID 
     Set Match = ROIDA.Find(ID) 
     If Not Match Is Nothing Then 
      ID = Match.Offset(0, -3) 
      End If 
     Next ID 


End Sub 

當我嘗試運行該腳本,我收到一個反對錯誤導向,從這一行:

Set ROIDA = WorksheetB.Range(Range("D7"), Range("D7").End(xlDown)) 

這是因爲我使用多張紙嗎?我正在努力不使用激活或選擇功能。

+0

您確定錯誤不是「Object ** required **」嗎? –

+3

您似乎正在使用一些未聲明的變量。確保在模塊的頂部指定了「Option Explicit」,並聲明所有變量。然後限定'Range'調用。不合格的'Range'調用隱含地引用活動表單,這絕對不是您打算在此處執行的操作。可能希望通過[Rubberduck檢查](http://rubberduckvba.com/inspections/list)運行該代碼,您將看到許多[Implicit actvie工作表參考](http://rubberduckvba.com/inspections/Details/ImplicitActiveSheetReferenceInspection)結果。 –

+3

@ Mat'sMug - 這是相當漂亮。 – SJR

回答

3

是的,如果運行宏時A/B未激活。您需要完全限定所有範圍和工作表。 A7之後沒有任何東西,最後還是繼續努力吧。

With WorksheetA 
    Set ROID = .Range(.Range("A7"), .Range("A7").End(xlDown)) 
'Or Set ROID = .Range(.Range("A7"), .Range("A" & Rows.count).End(xlup)) 
End With 

'Define range of attention lines and associated ROIDs 
With WorksheetB 
    Set ROIDA = .Range(.Range("D7"), .Range("D7").End(xlDown)) 
End With