要在 VBA 代码中使用VLOOKUP ,必须将引用样式设置为 R1C1,然后它应该可以工作。
在我看来,使用像 VLOOKUP 这样的 Excel 内置函数会产生更快的代码。另一方面,在 for-each 循环中搜索单元格的值是不好的做法,如果您有大量数据,则将花费大量时间。
这里有一个示例代码。它使用两张表:UserInfo、Maintenance。公式是根据模板字符串设置的,最后调用 Evaluate() 得到它的结果。HTH。
Public Sub test()
Dim pin
pin = VBA.InputBox("Enter PIN", "PIN")
If (pin = "") Then Exit Sub
Dim userInfoSheet As Worksheet
Set userInfoSheet = Worksheets("UserInfo")
Dim dataRange As Range
Set dataRange = userInfoSheet.Columns("a:b")
Dim initailsColumn As Byte
initailsColumn = dataRange.Columns(2).Column
Dim originalReferenceStyle
originalReferenceStyle = Application.ReferenceStyle
Application.ReferenceStyle = xlR1C1
Dim lookup As String
Const EXACT_MATCH As Integer = 0
lookup = "=VLOOKUP({PIN}, {DATA_RANGE}, {INITIALS_COLUMN}, {MATCH_TYPE})"
lookup = VBA.Replace(lookup, "{PIN}", pin)
lookup = VBA.Replace(lookup, "{DATA_RANGE}", dataRange.Worksheet.Name & "!" & dataRange.Address(ReferenceStyle:=xlR1C1))
lookup = VBA.Replace(lookup, "{INITIALS_COLUMN}", initailsColumn)
lookup = VBA.Replace(lookup, "{MATCH_TYPE}", EXACT_MATCH)
Dim result As Variant
result = Application.Evaluate(lookup)
Application.ReferenceStyle = originalReferenceStyle
If (Not VBA.IsError(result)) Then
Dim maintenanceSheet As Worksheet
Set maintenanceSheet = Worksheets("Maintenance")
maintenanceSheet.Range("k7").Value = result
Else
Dim parsedError As String
parsedError = ParseEvaluateError(result)
MsgBox "Error: " & parsedError, vbExclamation, "Error"
End If
End Sub
Private Function ParseEvaluateError(ByRef errorValue As Variant) As String
Dim errorNumber As Long
Dim errorMessage As String
errorNumber = VBA.CLng(errorValue)
Select Case errorNumber
Case 2000:
errorMessage = "#NULL!"
Case 2007:
errorMessage = "#DIV/0!"
Case 2015:
errorMessage = "#VALUE!"
Case 2023:
errorMessage = "#REF!"
Case 2029:
errorMessage = "#NAME?"
Case 2036:
errorMessage = "#NUM!"
Case 2042:
errorMessage = "#N/A"
Case Else
errorMessage = "Unknow"
End Select
ParseEvaluateError = errorMessage
End Function