Home » excel » excel – VBA VLookup Failing With Mixed Formatting

excel – VBA VLookup Failing With Mixed Formatting

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m doing what should be a fairly simple vlookup on a range with some mixed data:

enter image description here

Yet for some reason the search is consistently failing in instances where the search word is formatted as a number. When I write the same vlookup as a worksheet function, it works fine, but when done in vba, it returns #N/A (last column):

enter image description here

I’ve tried converting the search term to a string, but it hasn’t managed to make a difference. I’m sure this is a simple error, but good old google has turned up nothing. Below is the code I’m using to run the vlookup, but you’ll have to take my word that the helper functions are all working as intended. (I’m certain they are.)

Sub countOfWordInNonCompetitorGrounp()
Dim mainsheet As Worksheet
Dim lookupSheet As Worksheet
Dim outputColumn As Long
Dim outputRow As Long
Dim lookupValue As String
Dim lookupRange As Range

Set mainsheet = Sheets("UniqueWords")
Set lookupSheet = Sheets("Temp")
outputColumn = getFirstAvailableColumn(mainsheet, 1, 2)
Set lookupRange = getTempLookupRange
mainsheet.Cells(1, outputColumn) = "Count of Words in Non-Competitor Group"

For outputRow = 2 To getFirstAvailableRowOneBlankOk(mainsheet, 2, 1) - 1
    lookupValue = CStr(mainsheet.Cells(outputRow, 1))
    mainsheet.Cells(outputRow, outputColumn) = Application.VLookup(lookupValue, lookupRange, 2, False)
Next outputRow

End Sub
How to&Answers:

Change this line:

Dim lookupValue As String

to

Dim lookupValue As Variant

You are casting the numeric lookupValues to Strings, so they aren’t matched.