VBA vlookup reference in different sheet

后端 未结 4 1752
悲哀的现实
悲哀的现实 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:41

    Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

    To handle this case, try

    Sub Demo()
        Dim MyStringVar1 As Variant
        On Error Resume Next
        MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
          Worksheets("Sheet1").Range("A:C"), 1, False)
        On Error GoTo 0
        If IsEmpty(MyStringVar1) Then
            MsgBox "Value not found!"
        End If
    
        Range("E2") = MyStringVar1
    
    End Sub
    

提交回复
热议问题