【发布时间】:2019-01-04 16:19:23
【问题描述】:
我在尝试进行 Vlookup/Index-Match 时收到 1004 错误,或者根本没有结果。
我在 While 循环中尝试了 vlookup 和 Index /match。
到目前为止,我在许多宏中都使用了基本相同的循环,没有任何问题。我尝试调整格式(即使使用格式画家)。
我将查找的值隔离在一个新文件中,并只完成了查找部分。
注意:手动 Vlookup 或 index.Match 有效。
代码:
Sub lookup()
'Variables for the Vlookups
Dim newRow As Long
Dim newCL As String
newRow = 7
Dim rn As Range
Set rn = Worksheets("trysheet").Range("C:C")
Dim mrange As Range
Set mrange = Worksheets("trysheet").Range("A:A")
On Error Resume Next
'lookups
Do While Worksheets("test").Cells(newRow, 4).Value <> ""
newCL = Worksheets("test").Cells(newRow, 4).Value
Worksheets("test").Cells(newRow, 5) = Application.Index(rn,
Application.Match(newCL, mrange, 0))
newRow = newRow + 1
Loop
End Sub
我尝试过使用 Application.WorksheetFunction 而不仅仅是 Application。但后来我要么收到
1004 错误 - “无法获取 WorksheetFunction 类的 Match/Vlookup 属性”
或
应用程序定义错误
编辑:
我使用传统的 vlookup 功能(借助宏录制和修改我的循环)达到了所需的结果:
Sub lookup()
'Variables for the Vlookups
Dim newRow As Long
newRow = 7
Dim rn As Range
Set rn = Worksheets("trysheet").Range("C:C")
Dim mrange As Range
Set mrange = Worksheets("trysheet").Range("A:A")
On Error Resume Next
'
'Get Employee
Do While Worksheets("test").Cells(newRow, 4).Value <> ""
Worksheets("test").Cells(newRow, 5).FormulaR1C1 = "=VLOOKUP(RC[-1], trysheet!C[-4]:C[-2],3,0)"
newRow = newRow + 1
Loop
End Sub
我通常会尽量避免使用这种方法并坚持使用 application.WorksheetFunction 或 application.Vlookup(example),因为我发现它更干净并且会自动删除公式,但在这种情况下可以完成工作。
仍然帮助我理解为什么应用方法在这里不起作用,因为我第一次遇到这种情况。
yytsunamiyy 在下面有一些很好的建议,但仍然不完整。
【问题讨论】:
-
myrange 中是否存在 newCL 的值?
-
嗨,Nathan,是的,newCL 在 mrange 中,实际上在我的情况下,newCL 将采用的所有值都将匹配...