davidh120t
New Member
- Joined
- Apr 17, 2015
- Messages
- 3
I hope my favorite community can help me with a VBA problem that has been stumping me. I have a VBA macro where I want to insert a VLOOKUP formula into a cell. Sounds easy right? However, the workbook I am going to perform the lookup on is different that the one where the macro resides and I also want to use the name of that workbook (which I have captured and stored as a variable earlier) in the LOOKUP function. I have everything working until I get to the VLOOKUPand I cannot get the file name I stored to be used in the VLOOKUP function. I have placed my code below and highlighted the offending line of code. Thanks immensely in advance for any help! Also, I am trying to use a counter for the row number in that sheet which is going to be looked up.
Dim fd As FileDialog
Dim oFD As Variant
Dim fileName As String
Dim mywb As String
Dim subfile As String
Dim sheetname As String
Dim x As Integer
sheetname = "Sales"
mywb = ActiveWorkbook.Name
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Add "All Files", "*.*", 1
.Title = "Choose Webster Takeover File"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
fileName = oFD
Next oFD
On Error GoTo 0
End With
Workbooks.Open (fileName)
subfile = ActiveWorkbook.Name
Workbooks(subfile).Activate
Sheets(sheetname).Select
x = 3
Cells(x, 1).Select
'Loop until a blank row is found
Do While Cells(x, 1).Value <> ""
Cells(x + 1, 1).Select
x = x + 1
Loop
Workbooks(mywb).Activate
Cells(1000, 2).Select
ActiveCell.Value = subfile
Cells(1, 3).Select
Application.CutCopyMode = False
Cells(1, 3).Select
ActiveCell.Formula = "=VLookup(A1,'(subfile)Sales'!$a$3:$b$x,2,FALSE)"
End Sub
Dim fd As FileDialog
Dim oFD As Variant
Dim fileName As String
Dim mywb As String
Dim subfile As String
Dim sheetname As String
Dim x As Integer
sheetname = "Sales"
mywb = ActiveWorkbook.Name
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Add "All Files", "*.*", 1
.Title = "Choose Webster Takeover File"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
fileName = oFD
Next oFD
On Error GoTo 0
End With
Workbooks.Open (fileName)
subfile = ActiveWorkbook.Name
Workbooks(subfile).Activate
Sheets(sheetname).Select
x = 3
Cells(x, 1).Select
'Loop until a blank row is found
Do While Cells(x, 1).Value <> ""
Cells(x + 1, 1).Select
x = x + 1
Loop
Workbooks(mywb).Activate
Cells(1000, 2).Select
ActiveCell.Value = subfile
Cells(1, 3).Select
Application.CutCopyMode = False
Cells(1, 3).Select
ActiveCell.Formula = "=VLookup(A1,'(subfile)Sales'!$a$3:$b$x,2,FALSE)"
End Sub