是否可以从同一工作簿中的另一个 sheet 查找值?

Is it possible to lookup for a value from another sheet in the same workbook?

我有一个包含多个跨页的工作簿sheet。其中一个 sheet 称为 "Master Filtered",另一个称为 "MTL OR TOR" 我想用第二列中 "MTL or TOR" sheet 的查找值填充 "Master filtered" sheet 的列 K。我写了这段代码,但它不起作用。

Sub MTL_OR_TOR()
    Dim AcctNb As String
    Dim result As String


    Worksheets("Master Filtered").Activate 
    Dim lastrow As Long
    lastrow = Cells(Rows.Count, 1).End(xlUp).Row


    For G = 4 To lastrow

    AcctNb = Cells(G, 3).Value

    Set myrange = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered
    result = Application.WorksheetFunction.VLookup(AcctNb, myrange, 2, False)

    Range("K" & G).Value = result
    Next

End Sub

您知道为什么此代码不起作用以及如何修复它吗?

我在想也许我的错误是在以 Set myrange= Worksheets("MTL OR TOR") 开头的行中,但无法弄清楚。

Sub MTL_OR_TOR()
    ' Name your variables in a meaningful way and indicate their type
    Dim strAcctNb As String
    Dim strResult As String
    Dim lngLastRow As Long
    Dim lngLoop As Long
    Dim rngLookup As Range

    'Set your range and variables before you execute the code for readability
    Set rngLookup = Worksheets("MTL OR TOR").Range("AA4:AB685") 'Range in which the table MTL or TOR should be entered

    'Do not Activate or Select unless you really have to
    'Worksheets("Master Filtered").Activate

    With Worksheets("Master Filtered")

        lngLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For lngLoop = 4 To lngLastRow
            strAcctNb = .Cells(lngLoop, 3).Value
            strResult = Application.WorksheetFunction.VLookup(strAcctNb, rngLookup, 2, False)
            .Range("K" & lngLoop).Value = strResult
        Next

    End With

End Sub