工作表 class 的激活方法失败 - vlookup - vba

activate method of worksheet class failed - vlookup - vba

我想使用 VLOOKUP 命令并使用 sheet B 中的范围(不在激活的 A 中)。调用新工作sheet 给我一个错误“'runtime error 1004' activate method of worksheet class failed”

Public Sub Creation()

    Worksheets("A").Activate

    Randomize
    Dim code As String
    Dim hamid As Variant
    Dim Lookup_Range As Range
    Code = 100032
    Set Lookup_Range = Worksheets("B").Range("O1:P8")
    On Error Resume Next
    hamid = Application.WorksheetFunction.VLookup(code, Lookup_Range, 2, False)
    On Error GoTo 0

End sub

我试过用With命令调用新作品sheet但是没有成功。我是 VBA 的新手,所以请多多包涵。

您的查找范围似乎在工作表 B 中。请尝试在使用查找功能之前激活工作表 B。我在尝试在一个工​​作表上定义范围的同时激活另一个工作表时遇到了问题:

Public Sub Creation()

Worksheets("A").Activate

Randomize
Dim code As String
Dim hamid As Variant
Dim Lookup_Range As Range
code = 100032
'Try here:
Worksheets("B").Activate
Set Lookup_Range = Worksheets("B").Range("O1:P8")
On Error Resume Next
'or here:
Worksheets("B").Activate
hamid = Application.WorksheetFunction.VLookup(code, Lookup_Range, 2, False)
On Error GoTo 0
'also made 'Code' in lookup function 'code'.
End Sub