Save as CSV with semicolon separator - excel

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.

Related

How to copy file name to a cell, remove extension but preserve formatting

I have an excel VBA script that I am using to consolidate a bunch of reports (roughly 100) into a single worksheet, for each worksheet that I am adding I would like the file name to appear in a column, however I need to remove the extension ".xlsx" which I can do no problem however when I remove the extension the formatting of the cell changes, for example a file might be named 001.xlsx I remove the .xlsx and excel drops the leading 00's. How do I go about remove the filename extension but preserve the cell formatting?
Here is the code that I am using to add the filenames:
rngFile.Value = wbkSrc.Name
rngFile.Replace What:=".xlsx", Replacement:="", LookAt:=xlPart
Any help is greatly appreciated, thank you.
Adding a single quote (') in the beginning of the cell text will make Excel treat the cell content as text, so "001" will remain as it is after removing the ".xlsx" part.
cell.Value will be equal to the filename without the single quote.

Importing CSV file via VBA into Excel won't seperate data into different columns [duplicate]

This question already has answers here:
Workbooks.OpenText not parsing csv files properly Excel 2016
(4 answers)
Import semicolon separated CSV file using VBA
(1 answer)
Closed 2 years ago.
I have a CSV file filename.csv with the following content:
UID;Datum;Klasse;SendungsNr
6177;14.08.20;624;00340434299338038179
6178;14.08.20;624;00340434299338038186
6179;14.08.20;624;00340434299338038193
As far as I understand (here, here, here for the MS reference, etc. ...) this should import the file an insert the data into different columns:
Public Sub OpenCsvFile()
filepath = "C:\folder 1\folder 2\filename.csv"
Workbooks.OpenText Filename:=filepath, DataType:=xlDelimited, Semicolon:=True
End Sub
But it doesn't (see "update" below - seems to be a problem with the filename), it just uses the A column:
I tried specifying it over the other flag but the result stays the same:
Workbooks.OpenText Filename:=filepath, DataType:=xlDelimited, Other:=True, OtherChar:=";"
Since this can not be that difficult, I guess I'm just "blind" today, where's the problem?
Update: I found out that changing ".csv" to ".txt" seems to do the trick: it opens it into separate columns. Is that a bug or the desired behavior? Did I overlook anything in the MS reference? Now the question is, how do I get it to work without renaming the files (if it can be done at all)?
Update2: The solution, for whatever reason is to use Local:=True as a parameter (see the second link in the duplication notice, and some info is here as well). Why this has anything to do with the file suffix I can not fathom.

How to use Excel macro to add text to file name

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.

Fix csv files through Excel/Numbers [automatically through Python]?

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

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

Resources