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

久未见 提交于 2019-12-11 18:26:47

问题


I have a workbook with multiple spreadsheets. One of the sheets is called "Master Filtered" and the other is called "MTL OR TOR" I want to fill in the column K of the "Master filtered" sheet with a lookup value from the "MTL or TOR" sheet in the second column. I wrote this piece of code but it is not working.

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

Do you have any idea why is this code not working and how to fix it?

I was thinking maybe my error is in the line starting with Set myrange= Worksheets("MTL OR TOR") but couldn't figure it out.


回答1:


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


来源:https://stackoverflow.com/questions/56365578/is-it-possible-to-lookup-for-a-value-from-another-sheet-in-the-same-workbook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!