VBA vlookup reference in different sheet

后端 未结 4 1756
悲哀的现实
悲哀的现实 2020-12-17 06:29

In Excel 2007, I am looping through the values of column 4 in Sheet 2. Still in Sheet 2, I want to output the result of my vlookup formula into column 5. The vlookup formula

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 06:56

    The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

    The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

    1. The value is actually not present (pointed out by chris nielsen).

    2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

      Sub srch()
          Dim ws1 As Worksheet, ws2 As Worksheet
          Dim srchres As Variant
      
          Set ws1 = Worksheets("Sheet1")
          Set ws2 = Worksheets("Sheet2")
      
          On Error Resume Next
          srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
          On Error GoTo 0
          If (IsEmpty(srchres)) Then
            ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
          Else
            ws2.Range("E2").Value = srchres
          End If
      End Sub
      

    I will point out a few additional notable points:

    1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

    2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

    3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

    4. Both solutions by L42 qualify Ranges suitably.

    5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

提交回复
热议问题