Excel-VBA使用vlookup结果的左侧返回



我有一个基于简单查找的程序,它可以工作并返回正确的值。我想知道是否有办法合并 =LEFT 函数以使其返回 vlookup 结果的前两个字符。

ub Store_Lookup_left_test()
Dim rw As Long, x As Range
Dim extwbk As Workbook, twb As Workbook
Set twb = ThisWorkbook
Set extwbk = Workbooks.Open("H:********Master Store Info.xlsm")
Set x = extwbk.Worksheets("Info Sheet").Range("A1:C999999")
With twb.Sheets("Sheet1")
For rw = 1 To .Cells(Rows.Count, 1).End(xlUp).Row
.Cells(rw, 10) = Application.VLookup(.Cells(rw, 1).Value2, x, 3, False)
Next rw
End With

所以类比=Left(vlookup(a1,A1:C1,3,0),2),我可以做类似的事情吗.cells(rw, 10) = application.left(application.vlookup(.cells(rw, 1).Value2, x, 3, False),2)

目前,vlookup结果是

英国光学或爱尔兰光学

我希望它是

英国,伊尔州

您可以直接在 VBA 中使用Left函数,但您需要检查vlookup返回的内容,因为如果没有匹配项,它将返回Left无法使用的错误。

' Get vlookup result as variant so no error occurs if not string
Dim lookupresult As Variant
lookupresult = Application.VLookup(.Cells(rw, 1).Value2, x, 3, False)
' Check if vlookup returned an error (no match found)
If IsError(lookupresult) Then
MsgBox "Error with vlookup, no match found"
Else
' Get Left of string, up to 2 characters.
.Cells(rw, 10) = Left(lookupresult, 2)
End If

你不只需要:

.cells(rw, 10) = Left(application.vlookup(.cells(rw, 1).Value2, x, 3, False),2)

这使用内置的左VBA函数

最新更新