Using SaveAs Function, but periods change the fileformat - excel

I open an Excel file, fill some cells and then save it in a new folder.
The generated files include today's date that includes periods.
If the filename for example is "Template_Name_01.01.2022" the fileformat changes to .2022
Dim OriginalFileName As String
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Date
OriginalFileName = fileName
Dim fileNumber As Integer
fileNumber = 1
Do Until nameFree = True
nameCheck = Dir("G:\Argus\_Deal Tracker 3.0\Deals_Inv Mgmt\" & fileName)
If nameCheck = "" Then
xlBook.SaveAs fileName:="G:\Argus\_Deal Tracker 3.0\Deals_Inv Mgmt\" & fileName, FileFormat:=xlOpenXMLStrictWorkbook
nameFree = True
Else
fileName = OriginalFileName
fileName = fileName & " (" & fileNumber & ")"
fileNumber = fileNumber + 1
End If
Loop
Even though I determine the fileFormat it saves the file as .2022
Saved files
If I add an ".xlsx" extension to the filename it works for me but not on other PCs, I am guessing it is because they have file extensions hidden.
If they run the function they get this error.
Is there a way to prevent the file format changing if periods appear in the name?

You need to format the Date to remove the forward slashes / from the file name as they're not allowed. You also need to supply the file extension in the path.
So, change this:
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Date
to this:
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Format(Date, "dd.mm.yyyy") & ".xlsx" 'change to your extension

Performing the Save As from script, you have to contruct the whole filename, including the extension.
Basically you have to add something like:
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Date & ".csv"

Related

VBA to SaveAS with Filename, Specific Folder, and Date

I am trying to save file in a specific folder, add the filename, and add todays date. My VBA is not working. Any suggestions?
Sub SaveFile()
ActiveWorkbook.SaveAs ("G:\Product Support\Platinum\Agents Case Reports\Michael\Saved Client Reports\CAF\CAF Open Case Report.xlsx") & Date
End Sub
You can do this:
Public Sub SaveFile()
Dim formattedDate As String
formattedDate = Format(Now, "yyyy-mm-dd hh-mm-ss")
Dim filename As String
' path + filename + formatted date + extension
filename = _
"G:\Product Support\Platinum\Agents Case Reports\Michael\Saved Client Reports\CAF\" & _
"CAF Open Case Report - " & _
formattedDate & _
".xlsx"
ActiveWorkbook.SaveAs filename
End Sub
Whenever I output a date on a filename I always make sure it will sort chronologically. In the code above this is yyyy-mm-dd hh-mm-ss, which is year-month-day hour-minute-second. All numbers have leading zeroes, where necessary. An example from a few moments ago is "2021-08-03 17-58-59".
File name cannot contain "/" character which is in the date you should firstly store Current Date in a variable then replace "/" from it before passing it to file name
Sub SaveFile()
Dim CurrentDate as string
CurrentDate = Date
CurrentDate = Replace(CurrentDate, "/", "_")
CurrentDate = Replace(CurrentDate, ".", "_")
ActiveWorkbook.SaveAs ("G:\Product Support\Platinum\Agents Case Reports\Michael\Saved Client Reports\CAF\CAF Open Case Report " & CurrentDate & ".xlsx")
End Sub
This would work now.

Rename excel file with VBA

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.

Insert time stamp in file name with extension intact

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

How do I format a number to have at least 5 digits in a file name with a macro?

I'm working on a macro which involves generating a filename and saving an excel sheet as pdf with that name.
I was able to generate target folder name as follows.
user_name = Environ$("UserName")
file_dir = "C:\Users\" & user_name & "\Documents\Jobs\"
The file name is created as follows.
Job_No = Site & "SV" & num_from_cell
PDF = Job_No & ".pdf"
file_path = file_dir & PDF
Currently the above code returns MWSV234.pdf. I want it to be MWSV00234.pdf. num_from_cell comes from one of the cells in Excel sheet.
In short, I want to left pad num_from_cell to 5 digits. Could you please tell me how?
It would be safer to use Environ$("HomePath") to get the users home directory rather than Environ$("UserName")
file_dir = Environ$("HomePath") & "\Documents\Jobs\"
Then use Format to format with leading zeros for 5 numbers
Job_No = Site & "SV" & Format(num_from_cell, "00000")
PDF = Job_No & ".pdf"
file_path = file_dir & PDF

Excel VBA code to open a file

I created a macro button to open my daily files from a excel production sheet where I have all the my macro button for specific files.
The format for all my files are conventionally the same:
Businese Unit Name: YMCA
Year:2012
Month: April
Week: Week 2
Day: 12
File Name: YMC Template 041212.xlsm
I am having issue with the last excel file name extension.
how do I add the MyDaily Template and MyDateProd along with the .xlsm.
I have this -J:.....\& myDailyTemplate & myDateProd.xlsm") see below for entire file path names.
Sub Open_DailyProd()
Dim myFolderYear As String
Dim myFolderMonth As String
Dim myFolderWeek As String
Dim myFolderDaily As String
Dim myDateProd As String
Dim myBusinessUnit As String
Dim myDailyTemplate As String
myBusinessUnit = Sheet1.Cells(32, 2)
myFolderYear = Sheet1.Cells(11, 2)
myFolderMonth = Sheet1.Cells(12, 2)
myFolderWeek = Sheet1.Cells(13, 2)
myFolderDaily = Sheet1.Cells(14, 2)
myDateProd = Sheet1.Cells(15, 2)
myDailyTemplate = Sheet1.Cells(6, 5)
Application.Workbooks.Open ("J:\IAS\3CMC05HA01\IAC Clients\myBusinessUnit\myFolderYear\myFolderMonth\myFolderWeek\myFolderDaily\& myDailyTemplate & myDateProd.xlsm")
End Sub
Excel is looking for a file called:
"J:\IAS\3CMC05HA01\IAC Clients\myBusinessUnit\myFolderYear\myFolderMonth\myFolderWeek\myFolderDaily\& myDailyTemplate & myDateProd.xlsm"
since that is what is included in the quotes, but from your code, you appear to have a number of variables that are part of this string, you need to take them out of the quotes and concatenate them together. Try something like this:
"J:\IAS\3CMC05HA01\IAC Clients\" & myBusinessUnit & "\" & myFolderYear _
& "\" & myFolderMonth & "\" & myFolderWeek & "\" & myFolderDaily & _
"\" & myDailyTemplate & myDateProd & ".xlsm"
I added the continuation _ to make it more readable onthe screen here, but it is not necessary, you can put everything on one line together if you prefer.
Unless you need all of the myBusinessUnit, myFolderYear, etc variables elsewhere, I would think about doing it in some sort of array and then doing a Join function to concatenate everything. I, personally, find this easier to maintain going forward and easier to see the hierarchy in the folder structure rather than looking at a very long string and trying to find what part of the path is wrong.
Sub Open_DailyProd()
Dim pathParts(1 To 10) As String
Dim path As String
pathParts(1) = "J:"
pathParts(2) = "IAS"
pathParts(3) = "3CMC05HA01"
pathParts(4) = "IAC Clients"
pathParts(5) = Sheet1.Cells(32, 2)
pathParts(6) = Sheet1.Cells(11, 2)
pathParts(7) = Sheet1.Cells(12, 2)
pathParts(8) = Sheet1.Cells(13, 2)
pathParts(9) = Sheet1.Cells(14, 2)
pathParts(10) = Sheet1.Cells(6, 5) & Sheet1.Cells(15, 2) & ".xlsm"
path = Join(pathParts, "\")
Application.Workbooks.Open (path)
End Sub

Resources