vlookup value to be checked - String vs Long (or Integer)

ⅰ亾dé卋堺 提交于 2019-12-12 04:59:20

问题



I am trying to read in a value through vlookup and convert it to another value via the lookup table and I must be able to read in both numbers and letters.

Below is my code...

Dim myVLookupResult As String
Dim myRange As Range
Dim value As String
Dim value1 As Long

value = "30"            ' works only if there is a character in the string
value1 = 30             ' because this is a long, it can't have characters

With Worksheets("vlookup")

    Set myRange = .Range(.Cells(2, 3), .Cells(257, 9))

End With

myVLookupResult = WorksheetFunction.VLookup(value, myRange, 7, False)
MsgBox myVLookupResult

Now the part I can't figure out is the following and I really appreciate any help...

If I place the variable 'value' of type string into the command for .vlookup(value, myRange,7, False), I don't get an error as long as a character is in the string. If value is all numbers, I get an error of 1004.

I need to be able to read / support both numbers and letters for the input argument that is used as the lookup value in the vlookup command. Since I am designating value as type string, why would it fail if I enter 30 for example? Obviously a string is not always a string in vba.

Again any help is appreciated!


回答1:


It is contingent on what the Lookup range is.

If the the lookup range is text that looks like numbers then you need to use a string.

If the lookup range is numbers then you need to use a number. They need to match.

If the lookup range has both then you will need to do two vlookups and deal with the error.

Dim myVLookupResult As Variant
Dim myRange As Range
Dim value As String
Dim value1 As Long

value = "30"            ' works only if there is a character in the string
value1 = 30             ' because this is a long, it can't have characters

With Worksheets("vlookup")

    Set myRange = .Range(.Cells(2, 3), .Cells(257, 9))

End With


myVLookupResult = Application.VLookup(value, myRange, 7, False)
If IsError(myVLookupResult) Then myVLookupResult = Application.VLookup(value1, myRange, 7, False)
If IsError(myVLookupResult) Then
    MsgBox "Value not found as a number or string"
Else
    MsgBox myVLookupResult
End IF


来源:https://stackoverflow.com/questions/45762198/vlookup-value-to-be-checked-string-vs-long-or-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!