2017-08-11 58 views
1

我有一個基於簡單的查找程序,它的工作原理和返回正確的值。我想知道是否有一種方法可以合併= LEFT函數,使其返回vlookup結果的前兩個字符。Excel-VBA返回使用左側的查找結果

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結果是

英國光學,或愛爾蘭光學

,我希望它是

英國,IR

回答

1

你不只是需要:

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

此使用內置的Left VBA function

+0

剛纔想和它返回的 「運行時錯誤 '13',類型不匹配」 爲.Cells(RW,10)=左(Application.VLookup(.Cells(RW,1).Value2, x,3,False),2)我已閱讀文檔,非常感謝。我是否需要引入另一個變量並將其聲明爲String? – user8449681

+0

這可能意味着您從查找中得到空單元格結果。 首先我會改變Set x = extwbk.Worksheets(「Info Sheet」)。Range(「A1:C999999」) - 使用一個沒有空單元的範圍。 – Lobsterpants

+0

然後將application.vlookup(.cells(rw,1).Value2,x,3,False)賦值給一個變量,並在結果爲left之前檢查它是否爲空 – Lobsterpants

2

您只需直接使用Left功能VBA,但你需要檢查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 
+0

如果你添加一個lookupresult爲空的檢查,那麼這就是你想要的 - 除非tpe mismarch有其他原因嗎? – Lobsterpants

+0

使用Min是多餘的('Left(lookupresult,2)'將給出空字符串的正確結果)。當VLOOKUP沒有找到任何東西並返回'Variant/Error'時,'Type Mismatch'會在前一行中產生。 – BrakNicku

+0

你是對的@BrakNicku,我已經改正了我現在處理實際問題的答案 – Wolfie