Excel-VBA返回使用LOOK的查找结果

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

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 

那么我可以像.cells(rw, 10) = application.left(application.vlookup(.cells(rw, 1).Value2, x, 3, False),2)类似于=Left(vlookup(a1,A1:C1,3,0),2) .cells(rw, 10) = application.left(application.vlookup(.cells(rw, 1).Value2, x, 3, False),2)

目前的查找结果是

英国光学或爱尔兰光学

我想要它

英国,Ir

你不只是需要:

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

这使用内置的左VBAfunction

您可以直接在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