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.
Related
I am coding in VBA in excel. I am trying to export an excel file as a pdf. I want the name of the pdf file to be a combination of multiple things: Words (it's a name) from cell D3 & todays date & the word 'invoice'. Right now, the file exports, but it has the name 'combined' instead of showing Name09-12-202Invoice.
How do I get the 'combined' variable to reflect the Name & date & word invoice, and then get the pdf to have that name?
The code runs, just not as I am expecting. Since the exported pdf file has the name combined, instead of the information in the 'combined variable'.
I don't know if I need to have all of the dimensions for 'combined' to be a string. But if that's the case I don't know how to turn a date into a string dimension. Am I combining the clientname, client date, and client invoice variables together into one variable 'combined' properly? And primarily, why isn't the 'combined' at the end of saveLocation, not the information in the 'combined' variable?
Thank you to anyone who helps! I am new to VBA so I appreciate it!
Sub SaveActiveSheetsAsPDF()
'Create and assign variables
Dim saveLocation As String
Dim clientname As String
Dim clientdate As Date
Dim clientinvoice As String
Dim combined As String
clientname = Range("D3")
clientdate = Date
clientinvoice = "Invoice"
combined = clientname & clientdate & clientinvoice
saveLocation = "C:\Users\jessi\Documents\Info\combined.pdf"
'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=saveLocation
End Sub
Like this:
clientname = Range("D3").Value
clientdate = Format(Date, "yyyy-mm-dd") 'Make sure you don't end up with (eg) mm/dd/yyyy format...
saveLocation = "C:\Users\jessi\Documents\Info\" & _
clientname & "_" & clientdate & "_Invoice.pdf"
'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=saveLocation
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
I am new with VBA and I am struggling when trying to run a simple command.
I want to open a workbook (name = test.xlsx) which is saved in a specific path (C:\Users\u16086\Desktop\Folder) in my PC with a VBA code.
I defined two names in my first excel that are two parameters that I can modify if the path or the name of the file is different:
path: C:\Users\u16086\Desktop\Folder
file_name: test.xlsx
The code I wrote is:
Option Explicit
Sub openworksheet()
Dim path As String
Dim file_name As String
Workbooks.Open Filename:=path & file_name
End Sub
I ran the code, but it says there’s an error run-time error1004. How do I solve this problem?
You have defined two variables. You must allocate values to them and then build the path as shown below:
Sub openworksheet()
Dim path As String
Dim file_name As String
path = "C:\Users\u16086\Desktop\Folder"
file_name = "test.xlsx"
Workbooks.Open fileName:=path & "\" & file_name
End Sub
The path C:\Users\u16086\Desktop\Folder\test.xlsx can also be written as
"C:\Users\u16086\Desktop\Folder" & "\" & "test.xlsx"
so try
Workbooks.Open Filename:=path & "\" & file_name
Alternatively, you can check if the folder path ends with "\" or not. For example
Option Explicit
Sub openworksheet()
Dim path As String
Dim file_name As String
'~~> Change Sheet name and cell address accordingly
path = Sheets("Sheet1").Range("A1").Value
file_name = Sheets("Sheet1").Range("A2").Value
If Right(path, 1) <> "\" Then path = path & "\"
Workbooks.Open Filename:=path & file_name
End Sub
I get full path of an Excel file from a cell and use a function to retrieve the file name. I have final result as "abc.xlsx"
I need to insert a time stamp in the file name like "abc_02_11_19.xlsx".
I am able to generate the time stamp, the problem is appending it. The best I could think of was to remove the last five letters from the file name i.e. ".xlsx", append the time stamp and then append the ".xlsx".
The ending might also be ".xlsm", ".xlsb" or ".xls". I would need to extract everything after the dot.
Any better way to do this or if not, how best to do it elegantly?
Snippet of code, I am using-
oldname = FunctionToGetName(ThisWorkbook.Sheets("Sheet1").Range("B10").Text)
newname = FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B10").Text) & " " & oldname
newname = Replace(Replace(Replace(newname, ":", "_"), "/", "_"), "*", "_")
This inserts the time stamp before the file name. I need to append it after.
I've not tested this with your functions as I don't know what they do. But if I'm correct, the FunctionToGetName will return the filename as "filename.extention" and FileDateTime will return the date stamp you wish to attach.
With this you can get the filename by cutting everything after the "." with Left$(filename, InStr(oldname, ".") - 1). Then you can do the reverse of that and add the file extention back with Right$(oldname, Len(oldname) - InStr(oldname, ".")). And as per below, you can put pretty much anything in between.
Sub what()
Dim filename As String
Dim oldname As String
oldname = FunctionToGetName(ThisWorkbook.Sheets("Sheet1").Range("B10").Text)
Newname = Left$(filename, InStr(oldname, ".") - 1) & " " & FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B10").Text) & "." & Right$(oldname, Len(oldname) - InStr(oldname, "."))
End Sub
Check out FSO
Dim fso as object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oldname As String
Dim newname As String
oldname = "abc.xlsx"
newname = fso.GetBaseName(oldname) & "_" & Format(Now(), "mm_dd_yy") & "." & fso.GetExtensionName(oldname)
Debug.Print newname
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object
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