面向对象的错误 - 引用其他工作表?

时间:2017-02-16 22:13:55

标签: excel vba excel-vba

我正在使用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))

这是因为我正在使用多张床单吗?我正在努力不使用激活或选择功能。

1 个答案:

答案 0 :(得分: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