Reusability for a VLOOKUP macro - excel

I am trying to create a macro which includes a VLOOKUP but the VLOOKUP file would change each time. I would like the reference file in the VLOOKUP to be a variable. Ideally the macro would prompt the user to choose a file they wish to VLOOKUP from. So far I have this but it doesn't seem to be working...("test" is what the worksheet is named).
Sub VLOOKUP()
Application.ScreenUpdating = False
Dim myFilename As String
MsgBox "Please choose file with name to use in VLOOKUP formula.", vbOKOnly, "Choose file"
myFilename = CStr(Application.GetOpenFilename)
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'[" & myFilename & "]test'!C9:C10,2,0)"
End Sub
However, the VLOOKUP in the cell is not showing up how it should. e.g.
=VLOOKUP(B12,'[G:\OPS\National Pricing Data And Risk\Vehicle Pricing\VP Work\Gareth\Even Newer Toyota Macro Test\[Z401 Toyota Test COMPLETE.xlsx]test]Z401 Toyota Test COMPLETE.xlsx]'!$I:$J,2,0)
I'm not sure where the extra ]Z401 Toyota Test COMPLETE.xlsx] is coming from. Is there something I'm missing/not doing correctly?
Edit:
Sub VLOOKUP()
Application.ScreenUpdating = False
Dim fullPath As String
Dim tmpName As String
Dim tmpPath As String
Dim myFilename As String
fullPath = "G:\OPS\National Pricing Data And Risk\Calculators, Docs, Templates & Guides\Toyota Macros.xlsm"
tmpName = fso.GetFileName(fullPath)
tmpPath = fso.GetParentFolderName(fullPath)
myFilename = tmpPath & "\[" & tmpName & "]"
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'[" & myFilename & "]test'!C9:C10,2,0)"
End Sub

Isn't VLOOKUP a "reserved word" in Excel? Your function may not be working because you're trying to use an Excel function that already exists. Maybe try calling your function "MYVLOOKUP" and see if that works.
Brian

Excel doesn't like the way you've formatted your filename. You need to split it into directory and name.ext so you can format it like this:
'c:\path\to\file\[filename.ext]worksheetName'!F1
Edit
I forgot that this isn't as straightforward in VBA as it is in other languages. The easiest way is to use the FileSystemObject, but to use that you first have to reference it. You can see instructions on how to add the reference in this stackoverflow answer: https://stackoverflow.com/a/1755577/2295754.
And here's an example of how to use the FileSystemObject, in case you need a little more guidance than the other stackoverflow answer gave.
Dim fso As New FileSystemObject
fullPath = "D:\Ashby\Documents\test2.xlsx"
tmpName = fso.GetFileName(fullPath )
tmpPath = fso.GetParentFolderName(fullPath )
myFilename = tmpPath & "\[" & tmpName & "]"
Edit2
So, I intentionally left out the actual use of myFilename last time hoping you'd pick that up on your own. Oh well, here it is:
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'" & myFilename & "test'!C9:C10,2,0)"

Related

Unknown runtime error VBScripts - Write Formula into Excel

i'm trying put a formula in specific cell into a Excel, so i do a link between two excel for do this formula. I have this code, but i dont know, how use it for can obtein it that i will realize.
i'm amateur in this area and need to help for can do that.
my code is this
Set app = CreateObject("Excel.Application")
app.Visible = True
app.Workbooks.Open("C:\MODERNO\REPORTES\RESUMENFACTURA.XLS")
app.Worksheets(1).Cells(2, 17).formula = "=INDEX([Moderno.XLS]ART015!$J:$J;MATCH(P2; [Moderno.XLS]ART015!$P:$P;0))"
Write Formula to Excel
Since we are creating a new Excel instance, it is assumed that both files are closed (or at least the destination file).
The error is occurring because there is app.Workbooks but there is no app.Worksheets i.e. the 'parent-child' order is Application - Workbook - Worksheet - Range. You cannot skip one. You could have used something like
app.Workbooks(app.Workbooks.Count).Worksheets(1)...
but since we want to do other stuff with the workbook, it is easier (more readable) to use a variable (see dwb in the code) or alternatively the With statement.
Also, the formula is wrong. You cannot use the source workbook name without its path unless the workbook is open. To open it, you need to know its path. In VBA, you need to use commas instead of semicolons when using the Range.Formula property. To use semicolons, you can use the Range.FormulaLocal property. To allow the path, the file, or the worksheet name to have spaces, you need to use single quotes (') in the formula.
The Code
Option Explicit
WriteFormula
Sub WriteFormula
Const SourceFolderPath = "C:\MODERNO\REPORTES" ' adjust!
Const SourceFileName = "Moderno.XLS"
Const DestinationFolderPath = "C:\MODERNO\REPORTES"
Const DestinationFileName = "RESUMENFACTURA.XLS"
Dim DestinationFilePath
DestinationFilePath = DestinationFolderPath & "\" & DestinationFileName
Dim app: Set app = CreateObject("Excel.Application")
app.Visible = True
Dim dwb: Set dwb = app.Workbooks.Open(DestinationFilePath)
On Error Resume Next
dwb.UpdateLink dwb.LinkSources
On Error GoTo 0
dwb.Worksheets(1).Range("Q2").Formula _
= "=INDEX('" & SourceFolderPath & "\[" & SourceFileName _
& "]ART015'!$J:$J,MATCH(P2,'" & SourceFolderPath _
& "\[" & SourceFileName & "]ART015'!$P:$P,0))"
dwb.Close True
app.Quit
End Sub

VBA: For Loop hitting Automation Error -2147221080

Here is my code.
My purpose is, open a test excel and then save as a filename contained within the 'Test' sheet. I simply want to automate the task of saving an Excel for each of a list of filenames.
Sub POPButton1_Click()
Dim i As Long, LastRow As Long
LastRow = Test.Range("A" & Rows.Count).End(xlUp).Row
Dim filename As String
filename = ThisWorkbook.Path & Application.PathSeparator & "Test.xlsx"
Dim sjk As Workbook
Set sjk = Workbooks.Open(filename)
Dim saveName As String
For i = 1 To LastRow
saveName = Test.Cells(i, "D").Value
sjk.SaveAs ThisWorkbook.Path & "\" & saveName
sjk.Close
Next i
End Sub
The first excel is saved just fine, then I hit the bug. -2147221080 Automation error.
The line of code that highlights on debug is:
sjk.SaveAs ThisWorkbook.Path & "\" & saveName
I have looked around on this site and many others, as it appears a common bug, and I get the feeling it is an easy fix, but nothing I have tried has worked. I have re-written the code many times to get it to this point - I just can't see where the error is...
Ah! I think the answer is that you close the file but then never re-open it.
Move your Set sjk = Workbooks.Open(filename) inside your For loop at the top.
That should fix it for you.

VBA, File path dynamic date

I have a file that is placed in a folder, but the date is unknown to me, is there anyway I can pick it up regardless of the date?
FilePath = "\\0_Received\Business_Level_Report_yyyymmdd.xlsx"
The file name will be for example Business_Level_Report_20200729
The date will be unknown but it is the only file with Business Level Report as its prefix.
Can anyone help with this?
Maybe try this solution here: VBA partial file name
You can likely modify this just a bit to get what you're looking for.
For example, in your case you might try this:
myPath = "\\0_Received\"
fname = Dir(myPath & "Business_Level_Report*")
For example, this code opens the workbook named Business_Level_Report_blah_blah_blah without having to specify blah_blah_blah:
Here's the code if you want to run it, too:
Private Sub whatever()
Dim fname As Variant
Dim myPath As String
myPath = "C:\Users\beckj\"
fname = Dir(myPath & "Business_Level_Report*")
If fname <> "" Then
Workbooks.Open (myPath & fname)
MsgBox "File is open."
Else
MsgBox "ERROR."
End If
End Sub
For taday:
FilePath = "\\0_Received\Business_Level_Report_" & Format(Date, "yyyymmdd") & ".xlsx"
for "07/29/2020"
Dim D as Date
D = cDate("07/29/2020")
FilePath = "\\0_Received\Business_Level_Report_" & Format(D, "yyyymmdd") & ".xlsx"
Or if you do not care about a specific date, you must iterate between the folder workbooks and choose the appropriate one in this way:
If fileName like "*Business_Level_Report########.xlsx" then
FilePath = fileName
End If

Editing an automated naming macro in excel (based on PC name and date, with variable save path)

I'm currently trying to get an excel file to save into YYYYMMDD_fixed name piece_INITIALS OF LAST PERSON TO EDIT.
I'm using Environ function to call the User's and PC's name in a cell that i've found can be used to add to the name.
The issues i'm trying to fix are:
how can i define the save path to work on any PC regardless of user name, as current path has Users/my name/ , and up to 4 people with different PCs and names will edit this file. it should just save on Desktop on any of the 4 PCs
how can i modify the
strFile = "C:\Users\me\Desktop\" & Format(dtDate, "ddmmyyyy") & ".xlsx"
part so that it displays YYYYMMDD_name (i get this part ok) _ABC where ABC value is in cell A1 generated by the below attr function?
the function used is
Function attr(choice) As String
Select Case (choice)
Case "computer": attr = Environ("Computername")
Case "user": attr = Environ("UserName")
End Select
End Function
and the one i use to save (albeit a different format on a different file) is
Dim dtDate As Date
dtDate = Date
Dim strFile As String
strFile = "C:\Users\me\Desktop\" & Format(dtDate, "ddmmyyyy") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strFile, FileFormat _
:=51, CreateBackup:=False
Any help would be greatly appreciated!
Programming is not my main job, just trying to automate bits where possible, so go easy on me please :)
Maybe something like that will help:
Dim strFile As String, strUserName As String
Dim dtDate As Date
dtDate = Now
strUserName = attr("user")
strFile = "C:\Users\" & strUserName & "\Desktop\" & Format(dtDate, "ddmmyyyy") & "_" & Sheets("Sheet1").Range("A1").Value & ".xlsx"
MsgBox strFile
Note that I assigned the value of an active username to strUserName and I'm using it with your strFile. I also added Sheets("Sheet1").Range("A1").Value to the code (change sheet name accordingly). The final result will look like that:
C:\Users\username\Desktop\12082019_username.xlsx

Excel VBA using DIR function with wildcard and values from cell

I'm somewhat new to Excel VBA and am having trouble reading cell values and using them to find a file path and open the file. Here are some of the relevant facts (hopefully this is adequate specificity but please let me know if I am missing other relevant information).
I have the first name and last name of each person in adjoining cells, e.g. first name in F4 and last name in G4.
The files I am trying to open currently all start with "LastName, FirstName" but have different characters after them that don't follow a pattern. I'm trying to use a wildcard to make up for those unknown characters.
All the files are stored in "Z:\Documents\Warehouse Personnel Updates\" and they are all .xlsx files.
Eventually I'm going to create a loop to open multiple files for each person listed, but currently I am just focusing on getting one open.
Here is the code I currently have:
Sub findFile()
Dim Folder As String
Dim FileName As String
Dim FirstName As String
Dim LastName As String
FirstName = Range("F4").Value
LastName = Range("G4").Value
Folder = "Z:\Documents\Warehouse Personnel Updates\"
FileName = Dir(Folder & LastName & ", " & FirstName & "*.xlsx")
Workbooks.Open FileName
When I run this, I get "Run-time error '1004': Sorry, we couldn't find ." Just a space and then a period to end the sentence. It seems like it isn't reading the filename at all.
If anyone has insight to what I am missing, I would appreciate it! Thanks!
You can open a workbook using a wildcard in the Dir. This is just an example...
Dim sName As String
'Declare the variable for the workbook.
sName = Dir(ThisWorkbook.Path & "\*Smith_John*")
If sName <> "" Then
Workbooks.Open Filename:=ThisWorkbook.Path & "\" & sName
End If

Resources