How to use Excel macro to add text to file name - excel

I recorded a macro in excel to make some formatting changes to spreadsheets. I’m planning to run it every time I open a new export to begin working with it. I’d also like my macro to rename the file, based on the original name but adding more words.
For example:
Old file name: Sales.xls
New file name: 2019.07.10 Export Sales Backup.xlsx
The original file name will be different every time (“Sales”, “Mailing”, etc.), so I need the code to be based on the old name and not just dub everything Sales. The folder will always be the same—the file will always come from Desktop and get saved to Desktop.
I’ve read some questions about renaming but I can’t figure out how to parse the original file name to separate out the file path and only keep the bit I need. I’ve also seen questions that are about a batch rename, but I want to do this as part of an existing excel macro that I’ll already be running anyway. I’ve already read through these forums and figured out how to add the date and change the file format.
My current code says:
Sub Test()
FName = "C:\Users\Grace\Desktop\" & Format(Date, "yyyy.mm.dd") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=FName, _
FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
End Sub
I don't know where to start with trying to keep the original file name. Any help would be appreciated.

Related

How does Excel know that a file "was not recalculated before it was last saved". Can I trick Excel into thinking the opposite?

When linking workbooks in Excel, I often get an error like:
Links to xxxx.xlsx were not updated because xxxx.xlsx was not recalculated before it was last saved
This error pops up once for every linked value, which means in my case about 100 alerts I need to press OK for. Mysteriously, this alert comes even if xxxx.xlsx contains no formulas and hence no recalculation at all: it's completely full of values only.
So how does Excel know that a file has not been recalculated before saving? Is it looking at a particular xml value inside the ZIP file (xlsx) which I could tamper with? Is it looking at open date vs modified date that I could circumvent with the touch linux command? I'd like a solution Using the command line ubuntu if possible (I run windows WSL), so that I can use a script.
And what's more, xxxx.xlsx is really big, which over network (thanks COVID) at home is slow to open / recalc / save. So I really don't want to ever open this file in Excel.
Any ideas?
You could try adding this macro to your PERSONAL.XLSB file and then running it. It will ask you to select a file and then open it without allowing links to update.
Sub OpenWithoutUpdatingLinks()
Dim strFileName As String
strFileName = Application.GetOpenFilename
If strFileName <> "" Then Workbooks.Open FileName:=strFileName, UpdateLinks:=False
End Sub
This will allow you to open the file you're working on without getting the message about updating links.
However, if you actually need the links to update or need to create more links, then you need the linked file to be recalculated.
Let us know if you need instructions on adding a macro to your personal file and running it.

Closing workbook with partial file name

I have vba that works great to open a file based of a partial criteria met. but when I have multiple files open the file opening by the below VBA remains open when done and I am having trouble how to call that workbook back to close it seeing it opens off partial parameters being met. in quick summary the opencopy (opens a file), then in another vba I copy that data, and pastes it into another workbook (done in another VBA) when done i want to bring that workbook back up and just close it. if i do activeworkbook.close it closes the workbook i'm working on which i don't want. Help im stuck!
Sub OpenCopy()
Dim sPath As String
Dim sPartial As String
Dim sFName As String
sPath = "C:\" ' <<<<< change accordingly
sPartial = "AAA_" & Year(Now) & IIf(Len(Month(Now)) = 1, "0" & Month(Now), Month(Now)) &
IIf(Len(Day(Now)) = 1, "0" & Day(Now), Day(Now)) & "*.txt"
sFName = Dir(sPath & sPartial)
If Len(sFName) > 0 Then
Workbooks.OpenText sPath & sFName
Else
MsgBox "File not found.", vbExclamationEnd If
End Sub
Your problem is in "the other VBA". Try to force your project to comply with the rules by which VBA works.
That would mean to acknowledge that there is only one VBA. That VBA has procedures. You can call these procedures manually (which you probably do, and which leads you to talk of "the other VBA") or you can create a Main procedure that calls them for you, one after the other. The advantage of this would be that you can declare objects and variables in the Main which could be made available to all procedures, passed as arguments.
So, you would open a file, finding it by an abbreviated description of its name. You would assign this file to a variable, say File1, and now you could refer to it from anywhere in your project to read or copy from and to close it. You never need to know its name because you refer to it by the variable name to which it was assigned. VBA will assure that the name is unique.
As an alternative, you could of course take the file's complete name from the file after it was opened and then close the file by its complete name. In fact, the Dir function in your code does provide the complete name. So you could take it from there even before the file is opened. As I said, the problem is that the name would be in "the other VBA", an idea that isn't supported by VBA.
But, presuming that you want to continue with your piecemeal approach at least for the moment, wouldn't you be able to identify the file by the same partial details that led you to find it in the first place? I presume that the names of files you have open at the same time would differ in the "AAA" part. So, If Instr(ActiveWorkbook.Name, "AAA") = 1 Then would identify a file. You could loop through all open workbooks with For Each Wb In Application.Workbooks and check each name. You may have to add an input box to enter "AAA" another time because your different "VBAs" can't be made to talk to each other.
By the way, your beautiful partial string could be simplified using VBA's Format function. Try this.
sPartial = "AAA_" & format(date, "yyyymmdd")

Saving single sheet from workbook with defined destination and date stamp in file name name

I have almost no VBA experience but I have cobbled the below code together. I am looking to save a specific sheet from the an excel workbook in a particular file location with a unique file name(date stamp would work fine).
I am able to save off the individual sheet in the correct file type but I am having issues with the following:
The file is not saving to the correct folder. It is saving on my desk top, not the folder labeled "test files" on my desktop
I am unsure how to add a date stamp to the file name. The code is currently naming the file "test file". With the current code I was expecting the file to be name "COLLATERALUPLOAD"
Sub SaveCollateralUpload()
Application.ScreenUpdating = False
Sheets("COPY TO FOR UPLOAD").Copy
Sheets("COPY TO FOR UPLOAD").SaveAs "C:\Desktop\test files\COLLATERALUPLOAD.xls", FileFormat:=xlExcel8
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Sub
Any and all help would be incredibly appreciated!

Export to txt from VBA

I'm having some trouble exporting Excel files to txt files through VBA. The programm goes fine and generates a bunch of txt files with the information I want. The problem is that when exported, the txt file shows the date format as American, while I want it European dd/mm/yyyy. This doesn't happen when I save the txt manually. Here it is the code I'm trying to save the txt:
tmpFile = "C:\Users\z864451\Desktop\Prueba\AIMS\AIMS_" & Filename
ActiveWorkbook.SaveAs Filename:=tmpFile _
, FileFormat:=xlText, CreateBackup:=False
I have also tried to export to csv and then convert to txt but the same problem with the date happens again.
Any idea of how can I solve this?
Thanks
I'm guessing you want to use current date.
Below should do it:
tmpFile = "C:\Users\z864451\Desktop\Prueba\AIMS\AIMS_" & Format(Now, “dd/MM/yyyy”)
Source
Actually I realized the answer was just in changing the date format, when selecting the format there are two of them one is *14/03/2011 which is the one that was causing the problem, just changing it to 14/03/2001 solves the whole thing.
Thanks

Why is this file always saved as FALSE.xls?

I wrote a VB script that creates an .xls file, based on .xlt file. Then it calls a macro from the .xls file that populates it with information from a database. In the last step the script saves the .xls file on the disk.
I did this before with VB and Excel 2003. Now I upgraded to Excel 2007 and before it saves the file, a window pops up and tells me that:
"The following features can't be saved in macro free workbooks:
VB project
...some yada yada about what the Yes and No option do.
And the yes and no buttons in the dialog box.
"
I want the script to automatically select and execute Yes in the dialog box. But I can't figure how to do this. I've also posted the script I wrote.
If you have a better approach for this please share.
Thank you,
Steve
Sub Main()
Dim xl_app
Set xl_app = CreateObject("Excel.Application")
xl_app.Workbooks.Open("E:\Work\Send Mail\Clienti.xls")
'Run the macro
xl_app.Run( "ImportData(""Data Source=SFA;Initial Catalog=Campofrio;
Integrated Security=SSPI;Connect Timeout=3000"", -1, 47)")
xl_app.ActiveWorkbook.SaveAs FileName="E:\Work\Send
Mail\Clients.xls",FileFormat=xlNormal
xl_app.Quit
Set xl_app = Nothing
End Sub
Now the cod works but instead of saving the file at the specified location, it saves it in My Documents folder under FALSE.xls.
Merging responses from the two duplicate questions the poster asked:
1
Preventing False.xls when saving files in Excel
2
You are using named parameters in the .SaveAs wrong. When writing out the named parameter you'll have to do it in the format
FileName:="e:\myfile.xls"
Notice the colon before the equal sign.
If you just write Filename="myfile.xls" then its a boolean comparison that will return false. And thats why it save the file as false.xls.
Really funny error I think. ;)
I'm not sure if this is the problem, but shouldn't you just be saving as a .xlsm instead of .xls, which lets you save a macro-enabled workbook in Office 2007? You can check which version the macro is running on and if it's Excel 2007 then save as .xlsm, .xls otherwise...
Do you really need to save it with the macros included? If not, use:
ActiveWorkbook.SaveAs Filename:="E:\Work\Send Mail\Clients.xls", FileFormat:=xlNormal
EDIT: the key is that the extension used should match the FileFormat specified. The above works for me (to exclude macros) and the below works for me (to include macros). Neither has any popup, and both end up in the right directory (as the other poster mentioned, you have to have the := if you specify FileName; otherwise, use the form below.
ActiveWorkbook.SaveAs "c:\temp\wordmacros\mybook.xlsm", xlOpenXMLWorkbookMacroEnabled

Resources