VBA VLookUp not working

心已入冬 提交于 2019-12-11 09:16:27

问题


Hi I am trying to use the VLookUp function in VBA. It comes with the error, " Unable to get the VLookUp property of the worksheetFunction class" It is trying to take data from a sheet called 13.09.2017

Sub VLookUp()

Dim i As Integer

Dim k As Integer

For i = 1 To 10

 ThisWorksheet.Cells(1 + i, 11) = WorksheetFunction.VLookUp(Cells(1 + i, 2), Worksheets("13.09.2017").Range("B2:K11"), 10, False)

Next

End Sub 

enter image description here I hope you can help me


回答1:


ThisWorksheet is not part of the VBA object library. You probably need ThisWorksbook

This is how to do it, if you want to use the ActiveSheet(this is not adviseable, but it works):

Sub VLookUp()

    Dim i As Integer
    Dim k As Integer

    With ThisWorkbook.ActiveSheet
        For i = 1 To 10
            .Cells(1 + i, 11) = WorksheetFunction.VLookUp(.Cells(1 + i, 2), _
                 Worksheets("13.09.2017").Range("B2:K11"), 10, False)
        Next
    End with

End Sub



回答2:


Beside ThisWorksheet issue, your code will break on first instance where vlookup doesn't find value in range. If this is the only code you will be running, then add On Error Resume Next statement to avoid error.

Sub VLookUp()

    Dim i As Integer
    Dim k As Integer
    On Error Resume Next
    With ActiveSheet
    For i = 1 To 10
        .Cells(1 + i, 11) = WorksheetFunction.VLookUp(.Cells(1 + i, 2), _
            Worksheets("13.09.2017").Range("B2:K11"), 10, False)
    Next
    End With
End Sub


来源:https://stackoverflow.com/questions/46406632/vba-vlookup-not-working

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