Home » excel » excel – VBA VLookup allow the user to select the filename on directory

excel – VBA VLookup allow the user to select the filename on directory

Posted by: admin May 14, 2020 Leave a comment


I have been attempting to insert a VLookup formula into a column using VBA. The Table_array is variable and changes each month, so I would like a dialog box to specify the file I want to use. The Table_array is in an identical format each month and my formula so far is as follows:

Sub VlookupMacro()

Dim FirstRow As Long
Dim FinalRow As Long
Dim myValues As Range
Dim myResults As Range
Dim myFile As Range
Dim myCount As Integer

Set myFile = Application.GetOpenFilename("Excel Files (*.xls), *.xls")

Set myValues = Application.InputBox("Please select the first cell in the column with the values that you're looking for", Type:=8)

Set myResults = Application.InputBox("Please select the first cell where you want your lookup results to start ", Type:=8)

Range(myResults, myResults.Offset(FinalRow - FirstRow)).Formula = _
    "=VLOOKUP(" & Cells(FirstRow, myValues.Column) & ", myFile.value($A$2:$B$U20000), 5, False)"

If MsgBox("Do you want to convert to values?", vbYesNo) = vbNo Then Exit Sub

Columns(myResults.Column).PasteSpecial xlPasteValues
Application.CutCopyMode = False 

End Sub

I’m getting an issue with ‘myFile’ at the moment where the code doesn’t proceed past the Set = myFile line. Any suggestions or amendments would be most welcome. Other than that the variable file will never be longer than 20000 lines (which is why I have fixed the range in the formula) and we will always pick up column 5.

How to&Answers:

GetOpenFileName will not return an Object. Hence, you can’t Set the value.


FileName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls), *.xls", Title:="Please select a file") 
If FileName = False Then 
     ' User pressed Cancel
    MsgBox "Please select a file" 
    Exit Sub
    Workbooks.Open Filename:=FileName  
End If 


You’ve declared MyFile as a range, but you’re attempting to put a filename in the var. The GetOpenFileName function returns the filename, but doesn’t open the file. You’ll have to save the filename to a string variable, then open the workbook using that filename.