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
Related
I am new to VBA. I am using a "shell" macro to run another macro on a series of files. It won't save. I am going to include my code here and also a series of photos because the photos were the only way to show the result of hovering over the values in the code.
So, the error message is generating something I don't understand. But it is clear that the links in the code link to what the results should be, so I'm confused.
This is the code:
Sub SHELLforMacros()
Dim wbMatrix As Workbook
Dim strFileName As String
Dim strFileName As String
Dim newFileName As String
Dim strPath As String
Dim strExt As String
Dim objWorkbook As Workbook
Dim ws As Worksheet
Dim Sheetname As Worksheet
Set Sheetname = Worksheets(1)
Dim Worksheet As Worksheet
Dim rng As Range
Set rng = Range("A2")
strPath = "C:\Users\myname\Desktop\All_mricgcm3_files\45\Fall45\test\"
strExt = "csv"
strFileName = Dir(strPath & "*." & strExt)
While strFileName <> ""
Set wbMatrix = Workbooks.Open(strPath & strFileName)
Application.Run "'C:\Users\myname\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB'!Graph_NEW"
strPath = "C:\Users\myname\All_mricgcm3_files\45\Fall45\test\"
newFileName = Sheetname.Range("A2").Value
ActiveWorkbook.SaveAs fileName:=strPath & newFileName, FileFormat:=51
ActiveWorkbook.Close SaveChanges:=True
Wend
End Sub
What this macro is supposed to do is open a file, run another macro on the file (creating a graph), and then save the file with the same name but as an .xlsx file. Then open the next file in the folder and do the same, until it runs out of files. I realize the code may not be the most current. It is cobbled together from things I've found online. Thanks for any help.
Edit: UPDATE - I removed all the section on saving and closing the file from the "shell" macro and put it into the "Graph_NEW" macro. Now the "shell" macro is running fine. But I am running into the same issue with the "Graph_NEW" macro now. It is exactly the same error message as highlighted in the first image, only each time there is a new 8-digit alphanumeric "filename" that it is looking for. This seems like a very specific thing.
I changed the section in the following ways, successively, in an attempt to debug. I added With and End With around the section:
With WB
ActiveWorkbook.Save
newFileName = Sheetname.Range("A2").Value
strPath = "C:\Users\qmontana\All_mricgcm3_files\mric45\Fall45\test\"
ActiveWorkbook.SaveAs fileName:=strPath & newFileName & ".xlsx", FileFormat:=51
ActiveWorkbook.Close SaveChanges:=True
End With
I changed the name of the folder from "45" to "mric45" thinking that maybe it didn't like a number as a folder name.
I removed the "backslash" at the end of the strPath--and then the 8-digit alphanumeric string showed up as an error after the Fall45 folder, like this "C:\Users\myname\Desktop\All_mricgcm3_files\45\Fall45\777GTY78". Yet, as I've shown in the images, all indications are that it knows what file it is working with. There are no "blank spaces" in the pathname.
I tried taking the underscores out of the folder "All_mricgcm3_files".
I moved the line newFileName = Sheetname.Range("A2").Value to come before the strPath line.
Where is this 8-digit alphanumeric "filename" coming from?? (See error code, first image.)
Ok, it was a very simple thing, in case anyone else runs into this problem.
Took me two days to find out though --> I had somehow dropped a folder layer in the path name. The catch? The alphanumeric string was showing up at the end of the path name, not where the folder layer was missing. That's why I was thrown off because my focus was on the ending.
When I added that folder\ back in, I had no more problem with saving and the macro ran fine.
I'm creating an excel file from nothing, adding content and saving it. I want to rename the excel file once I saved it, using VBA code. The file I want to rename isn't the same file in which I'm writing the code.
Currently I'm trying to do it this way (this is a snippet of my code, just to show how I'm saving the file):
Dim workbook1 As Workbook
Dim name As String, lastcell As String
Dim oldname As String, newname As String
Set workbook1 = Application.Workbooks.Add
name = "financial report - "
workbook1.SaveAs ThisWorkbook.Path & "\" & name & ".xlsx"
'lastcell has a date that I want in my new title
lastcell = Range("A1").End(xlDown).Text
oldname = ThisWorkbook.Path & "\" & name & ".xlsx"
newname = ThisWorkbook.Path & "\" & name & lastcell & ".xlsx"
Name oldname As newname
But when I run it I get this:
The value in my lastcell variable is supposed to be in a date format like this dd/mm/yyyy. The exact cell I'm trying to copy and use as part of the name of my new excel is 05/02/2021.
The value in name by the end of the sub should be financial report - 05/02/2021.
I'm gonna be surprised if this hasn't been asked before. Does anybody know what I'm doing wrong or have any recomendations for my code?
You need to provide a date value which can work as part of a filename:
lastcell = Format(Range("A1").End(xlDown),"yyyy-mm-dd")
Check out
https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.savecopyas
workbook1.SaveCopyAs newname
There you have your issue 05/02/2021 cannot be part of the file name as a slash / is not allowed in file names. Slash and backslash are considered to be path seperators.
Try the following: Make sure the variables are declared properly as below, to ensure the date is read as numerical date and not as some text that cannot be formatted.
Dim Name As String
Name = "financial report - "
Dim ReportDate As Date
ReportDate = Range("A1").End(xlDown).Value 'make sure you read the `.Value` not `.Text`
workbook1.SaveAs ThisWorkbook.Path & "\" & Name & ".xlsx"
workbook1.SaveCopyAs ThisWorkbook.Path & "\" & Name & Format$(ReportDate, "yyyy-mm-dd") ".xlsx"
Also use .SaveAs to save the original workbook and .SaveCopyAs to save the copy with the date attached.
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
I'm trying to open, and import values to a workbook from another workbook. Both files are in SharePoint and in the same directory.
It works as long as the target file has a specific name. But the file will have a variable start and ending in the name. 5 varying numbers + name + varying date (72262-Faktureringsplan-2018-11-16).
I've tried using * but it seems it doesn't work with SharePoint. How can I use some kind of "wildcards" for accessing files names in SharePoint?
This is the part of the code that will load the file:
Sub faktureringsplan()
Dim FileName As String
FileName = ActiveWorkbook.Path & "\72262-Faktureringsplan-2018-11-16.xlsx"
Set wb = Workbooks.Open(FileName)
ThisWorkbook.Sheets(1).Range("B10:B31").Value = wb.Sheets(1).Range("B2:B23").Value
MsgBox ("Ferdig")
wb.Close
End Sub
This code is trying to look for very specific filename with '\72262-Faktureringsplan-2018-11-16.xlsx'
on line:
FileName = ActiveWorkbook.Path & "\72262-Faktureringsplan-2018-11-16.xlsx"
The way wildcard("*") works, is that it replaces the part you want to match with anything. So a simple change from the above to
"\72262-Faktureringsplan-*.xlsx"
would return filename that has any date starting with '72262-Faktureringsplan' in your case.
You could also make use of VBA's date function to find a matching filedate that has the same date as today's date.
Format(date, "YYYY-MM-DD")
would return today's date in the format "2018-11-16" (date of this reply).
Essentially, you can do something like this:
FileName = ActiveWorkbook.Path & "\*-Faktureringsplan-" & Format(date, "YYYY-MM-DD") & ".xlsx"
This would match the following: ANYTHING-Faktureringsplan-TODAY'S_DATE.xlsx
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)"