Reputation: 1886
I'm keep running into a error when trying to use worksheetfunction.Vlookup. The error is given as:
Run-Time Error 1004 (Application-defined or object-defined error)
The error occurs in the code for "g". My code is:
Sub Rankings()
Dim f As Variant
Dim n As Variant
Dim h As Variant
Dim e As Integer
Dim d As Integer
Dim c As Integer
Dim g As Variant
d = 2
e = 2
While d < 7
c = 2
Worksheets("Sheet1").Activate
While Cells(c, 1) <> vbNullString
n = Right(Cells(c, 1), Len(Cells(c, 1)) - 1)
h = Worksheets("Sheet2").Cells(Worksheets("Sheet2").Rows.Count, e).End(xlUp).Row
g = WorksheetFunction.VLookup(n, Worksheets("Sheet2").Range(Cells(3, e - 1), Cells(h, e)), 2, False)
f = WorksheetFunction.Rank_Eq(g, Worksheets("Sheet2").Range(Cells(3, e), Cells(h, e)), 1)
If Not IsError(f) Then
Cells(c, d) = f
Else
Cells(c, d) = WorksheetFunction.Max(Worksheets("Sheet2").Range(Cells(3, e), Cells(h, e)) + 1)
End If
Wend
Wend
End Sub
Basically, what I am trying to do is to rank the values in sheet 2, column 2, and put them into the cells in column 2 in sheet 1, corresponding to the relevant golfer.
Any suggestions on how to fix the error?
Upvotes: 0
Views: 1533
Reputation: 3324
A common error. Having activated Sheet1, you attempt to perform a vlookup in a range located on Sheet2.
g = WorksheetFunction.VLookup(n, Worksheets("Sheet2").Range(Cells(3, e - 1), Cells(h, e)), 2, False)
HOWEVER, your Range that you construct as a parameter to the Vlookup is using a Cells call to the active sheet(Sheet1).
It is advisable to get handles to your worksheets when switching between sheets often, like so:
Dim ws1 As Worksheet
Dim ws2 As Worksheet
set ws1 = Worksheets("Sheet1")
set ws2 = Worksheets("Sheet2")
then you should do like:
g = WorksheetFunction.VLookup(n, ws2.Range(ws2.Cells(3, e - 1), ws2.Cells(h, e)), 2, False)
Upvotes: 4