尝试使用worksheetfunction.Vlookup时,我一直遇到错误。错误如下:
运行时错误1004(应用程序定义的错误或对象定义的错误)
错误发生在" g"的代码中。我的代码是:
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
基本上,我要做的是对第2页第2列中的值进行排名,并将它们放入第1页第2列中与相关高尔夫球手相对应的单元格中。
有关如何解决错误的任何建议?
答案 0 :(得分:4)
常见错误。激活Sheet1后,您尝试在Sheet2上的范围内执行vlookup。
g = WorksheetFunction.VLookup(n, Worksheets("Sheet2").Range(Cells(3, e - 1), Cells(h, e)), 2, False)
HOWEVER ,您构建为Vlookup参数的Range使用了对 活动工作表(Sheet1)的单元格调用。
建议在经常切换工作表时获取工作表的句柄,如下所示:
Dim ws1 As Worksheet
Dim ws2 As Worksheet
set ws1 = Worksheets("Sheet1")
set ws2 = Worksheets("Sheet2")
然后你应该这样做:
g = WorksheetFunction.VLookup(n, ws2.Range(ws2.Cells(3, e - 1), ws2.Cells(h, e)), 2, False)