你的代码有两个问题:
对于worksheetfunction.vlookup,搜索范围不能不稳定。
所以解决这个问题的方法是使用额外的变量来永久化
如果worksheetfunction.vlookup找不到搜索值,则会出现错误,这种情况下你需要使用额外的错误处理操作
lookupVal 必须声明为as Range,因为单元格的格式(查找范围和查找值)可能不同,但在您的代码中,单元格值总是会转换为字符串类型,而您不会如果将数字转换为字符串,则能够找到数字
myString 也需要声明为as Variant,原因与“3”中描述的相同。例如,单元格的类型可以是 double,但您的代码会将其转换为 string
所以,您的更新代码如下,工作正常
Sub test()
Dim lookupVal As Range, myString As Variant, Rng$, n&
n = Sheets("b").[B:B].Cells.Find("*", , , , xlByRows, xlPrevious).Row
On Error Resume Next
For i = 1 To n
Set lookupVal = Sheets("b").Cells(1 + i, 2)
Rng = Range(Cells(9, 3), Cells(n + 8, 3)).Address
myString = WorksheetFunction.VLookup(lookupVal, Sheets("a").Range(Rng), 1, False)
If Err.Number > 0 Then
Sheets("b").Cells(1 + i, 3) = ""
Err.Clear
Else
Sheets("b").Cells(1 + i, 3) = myString
End If
Next i
End Sub
下面的替代方式
Sub test()
Dim cl As Range, Dic As Object
Set Dic = CreateObject("Scripting.Dictionary"): Dic.Comparemode = vbTextCompare
With Sheets("a")
For Each cl In .Range("C9:C" & .Cells(Rows.Count, "C").End(xlUp).Row)
If Not Dic.exists(cl.Value) Then Dic.Add cl.Value, cl.Row
Next cl
End With
With Sheets("b")
For Each cl In .Range("B2:B" & .Cells(Rows.Count, "B").End(xlUp).Row)
If Dic.exists(cl.Value) Then cl.Offset(, 1).Value = cl.Value
Next cl
End With
Set Dic = Nothing
End Sub