I am trying to write a code that takes a .xls file and modifies the values in it after which saves it in a set location with a set filename that may always change based on the "NewSaveName" string but it gives me an error "Close' of object '_Workbook' failed" and I can't figure out why. Sometimes it works and sometimes it doesn't. The code I have written:
Workbooks("FormatSketch_DesignTable").Close SaveChanges:=True, Filename:="E:\FORMAT\Temp\" & SaveName & ".xls"
Could someone, please, help me solve this one?
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.
I'm working with some CSV files which have been created incorrectly. There are quotations and commas interconnected, and I keep getting parsing errors from pd.read_csv, even after replacing all column-separating commas with tabs.
Nevertheless, Numbers (Apple's Excel) can read the file perfectly, and, after re-saving it as csv, Pandas can generate data frames seamlessly. Thus, I wanted to know if there was a way, preferentially through Python, to automate this import-export in Numbers/Excel (maybe an API?) to fix my CSVs, or maybe find out what they do to correct them.
EDIT: The CSV rows look as following:
"id","lastVisitTimeLocal","lastVisitTimeUTC","title","url","typedCount","visitCount",""[]"_id","_id"
8986,"06/03/2018, 20:00:48","3/6/2018 2:30:48 PM","","https://chrome.google.com",0,1,3000001,2000001
Although some titles contain commas and some links contain quotation marks, so I keep getting parsing errors, despite Numbers/Excel parsing them seamlessly.
EDIT2: I'm looking for a pipeline that does the following:
file.csv --excel_engine--> file.xlsx --excel_engine--> file2.csv
Have you tried setting quoting and doublequote in pd.read_csv()? It's odd to me that Pandas can't read a csv that Excel can (i usually have problems with Excel instead; the only issue i've had with Pandas is NUL characters).
Alternatively you can also run this in VBA:
Sub openCsvAndSave()
Dim csv_paths, path
csv_paths = Array(path1, path2, ...) ' Set your csv paths here '
For Each path in csv_paths
Dim NewWb As Workbook: Set NewWb = Workbooks.Open(path)
NewWb.SaveAs Left(path, Len(path) - 4) & "_2.csv", xlCSV
Next path
End
I'm currently use this function for saving, but I have a problem with it:
Private Sub spara()
ActiveWorkbook.SaveAs Filename:="T:\filepath+ ActiveWorkbook.Name", _
FileFormat:=xlCSV, CreateBackup:=False
End Sub
It automatically saves with , but I need it to save with ; in its file. Is it possible to change how it saves somehow?
I've tried googling around for this issue, but all macros regarding .csv file saving are just how to save in .csv and how to split multiple sheets to .csv .
Which language does your Excel use? If your native language uses ";" as default, you can pass the parameter "local:=True"
ActiveWorkbook.SaveAs Filename:="C:\Temp\Fredi.csv", FileFormat:=xlCSV, CreateBackup:=False, local:=True
If not, your only choice is searching and replacing afterwards...
I had been looking this up to help resolve a similar issue I was having,
I had an excel sheet that I export to a csv file, this is then uloaded elsewhere but requires the use of semicolons rather than commas for the character seperation, this worked fine when i was manually exporting the file as i had already changed the following
Control Panel >> Region and Language >> additonal settings >> List separator
from comma to semicolon.
But when i tried to automate via VBA it defaulted back to comma,
to fix I added the local paprameter as suggested by Christian Sauer above which then picks up the fact that i have changed my regional settings.
ActiveWorkbook.SaveAs Filename:="Filename.txt", FileFormat:=xlCSV, CreateBackup:=False, Local:=True
Thanks to Christian for the pointer.
Change Excel Options (Advanced, Editing options) to set Decimal separator to , (obviously (!))
I solved it adding "SaveChanges:=False" when closing workbook
With ActiveWorkbook
.SaveAs Filename:="T:\filepath+ ActiveWorkbook.Name", FileFormat:=xlCSV, Local:=True
.Close SaveChanges:=False
End With
It's quite possible this problem is not solvable using Excel VBA only. The problem is, while Excel Save As... uses machine locale define list separator value, Excel VBA always uses en-US locale, thus, it always uses , as a list separator.
I would recommend saving a CSV and then use custom console app/script for postprocessing. There is plenty of CSV parsers available which can read a ,-csv and then save it as ;-csv.
For people having issues with this code
dim wa as Workbook
Workbooks.OpenText FileName:=path2file, _
DataType:=xlDelimited, Semicolon:=True, Local:=True
set wa = ActiveWorkbook
wa.SaveAs FileName:=path2file, FileFormat:=xlCSV, _ ConflictResolution:=xlLocalSessionChanges, Local:=True
wa.Close False
The second line is really important, if wa.Close False is not there it will ask for approval to save, or if wa.Close True it will replace the ";" for ",".
After going into local settings and making ";" the list delimiter, VBA was still separating with a ",". Modified the code to the above and it was done.
Hope this throw some light for some
Great answers here, but they didn't work for me, because I'm trying to create a tool that will work for any user on their own computer, and I don't want to have to set up this locale stuff on everybody's PC. I even tried rolling my own CSV exporter using FileSystemObject, but the destination path name is on SharePoint, so that failed too.
Then I stumbled upon a very simple workaround: create a new worksheet that concatenates all your information into one column, separated by semicolons, e.g.:
CONCAT('Old WS'!A1,";",'Old WS'!B1,";",'Old WS'!C1,";",'Old WS'!D1,";",'Old WS'!E1)
Then add some code like this to export it:
Call Worksheets("Export WS").Copy
ActiveWorkbook.SaveAs Filename:=CSVname, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Because it's all in one column, Excel won't add its own delimiters!
Expanding on James Fingas's answer.
SOLUTION:
Concatenate all your information from multiple columns into one column and separate the data in the concatenated string by your separator of choice - i.e. the semicolon. Then copy the one column to a new file and save it.
LIMITATION:
However, beware that this solution is flawed when comma is present somewhere in the concatenated data as the concatenated string becomes wrapped by double quotes - see explanation below.
(1) When you save the file, VBA assumes that comma is the delimeter for the file. VBA also sees that comma is present in your string. Thus, in order to protect against future splitting of the string, VBA wraps the concatenated string in double quotes.
(2) You can try to bypass this problem by setting the system separator to semicolon and saving the file with the "Local:=True" parameter. However, now VBA knows that semicolon is the delimeter for the file. VBA also sees that semicolons are present in your string. Thus, in order to protect against future splitting of the string (VBA doesn't now that you actually want to split using the semicolons), VBA wraps the concatenated string in double quotes.
My issue is this.
I read in a series of filenames using a wildcard, so that the end of the filename is unknown, and the extension is either .xls or .xlsx. So, the wildcard is something like :
beginningOfFilename_*.xls*
I then want to take each file, after I have manipulated it, and save it with the same name, but as a .csv (comma seperated value file). In vba for excel, can I just specify the format and it will take care of the extension, or do I have to somehow pull off the( unknown) extension, and append .csv
If the second case is neccessary how would you approach this problem, I don't know where to start, since part of the filename is unknown, and I am not sure how to manipulate strings in vba.
I'm a VBA beginner.
Any help will be appreciated, thanks.
The line you want is :
Mid(sFile, 1, InStrRev(sFile, ".")) & "csv"
Where sFile is the file name with any extension.
Split(sFile, ".")(0) & ".csv"
where sFile is the filename
To get a path and name of your file without extension use.
Dim StrFileName as string
StrFileName= split(ThisWorkbook.fullName,".xls")(0)
Now save your Csv using StrFileName content.
[]´s