左(VLookup)vba

时间:2018-04-17 13:24:14

标签: excel-vba vba excel

我遇到了Vlookup的问题。 下面的代码与代码返回数字一样长,但是当它是文本时,它不会返回文本中的前3个字母。

任何人都无法解决这个问题?

最好的问候kjeld

Sub test()

Dim AntalO As Integer
Dim AntalM As Integer
Dim res As String 
Dim CountryRange As Range, InitialRange As Range, C As Range

AntalO = Worksheets("ark1").Cells(2, 4).Value    
AntalM = Worksheets("ark1").Cells(4, 4).Value   

Set CountryRange = Sheets("Hoved").Range(Cells(2, 6), Cells(AntalM, 6))    
Set InitialRange = Sheets("ordre").Range("A1:R50000")     

For Each C In CountryRange    
    res = Left(Application.VLookup(C, InitialRange, 19, False), 3)    

    If Not IsError(res) Then   
        C.Offset(0, -1).Value = res
    End If

Next C

End Sub

1 个答案:

答案 0 :(得分:0)

下面的代码怎么样,如果值是数字,这将得到Vlookup返回的前三位数,但如果它是一个字符串,那么它将返回完整的值:

Sub test()

Dim AntalO As Integer
Dim AntalM As Integer
Dim res As String
Dim CountryRange As Range, InitialRange As Range, C As Range

AntalO = Worksheets("ark1").Cells(2, 4).Value
AntalM = Worksheets("ark1").Cells(4, 4).Value

Set CountryRange = Sheets("Hoved").Range(Cells(2, 6), Cells(AntalM, 6))
Set InitialRange = Sheets("ordre").Range("A1:R50000")

For Each C In CountryRange

    If IsNumeric(Application.VLookup(C, InitialRange, 19, False), 3) Then
    'if value returned by Vlookup is numeric then
        res = Left(Application.VLookup(C, InitialRange, 19, False), 3)
        'get the first three digits
    Else 'if the value returned is not numeric
        res = Application.VLookup(C, InitialRange, 19, False)
        'return the full value
    End If

    If Not IsError(res) Then
        C.Offset(0, -1).Value = res
    End If

Next C

End Sub