问题
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