Question

I need to save several xlsm files as CSV in order to import them in other programs (such as R etc.). Well I've written the necessary import routines in all the other programs and they work very nicely with case 1:

Case 1: Manually saving an xlsm as CSV If I use this option and manually save each file as CSV and click YES on all prompts, I get a .csv file which looks very similar to a normal Excel file when opened again within excel. It is a standard column view, and nothing comma separated etc. (maybe it is, but it doesn't look that way..)

Case 2: Saving an xlsm from VBA as CSV Well here I get a completely different file when opened again in Excel. This one looks like a "real" csv file with all values being comma separated.

My questions are: 1. Why is there any difference? 2. How can I programmatically reach Case 2 from VBA? Or is that impossible?

If 2 is impossible I have to rewrite my import code routines to handle the "normal" csv file...not very difficult but still a lot of work and I'm really wondering why there even is a difference..

Was it helpful?

Solution

Q1: I don't think there is a difference, at least not in an example I pulled together. Q2: Try this out:

I've got 3 example XLSM files in C:\stack\folder1 as pictured below:

start2

Each file has a single data sheet, which we'll turn into CSVs:

start

I'm sure your routine is much more complicated, but to test the CSV output I'm just going to loop through the files and save each as xlCSV:

Option Explicit
Sub TestCSVOutput()

Dim DataBook As Workbook
Dim DataSheet As Worksheet
Dim FilePaths(3) As String
Dim FileIdx As Long

'set up file paths for test
FilePaths(1) = "C:\stack\folder1\test_file_01.xlsm"
FilePaths(2) = "C:\stack\folder1\test_file_02.xlsm"
FilePaths(3) = "C:\stack\folder1\test_file_03.xlsm"

'loop through array and save each file as a CSV
Application.DisplayAlerts = False
For FileIdx = 1 To UBound(FilePaths)

    Set DataBook = Workbooks.Open(FilePaths(FileIdx))
    Set DataSheet = DataBook.ActiveSheet
    DataBook.SaveAs FileFormat:=xlCSV '<~~ the save step
    DataBook.Close

Next FileIdx
Application.DisplayAlerts = True

End Sub

Once the script completes, I end up with three CSV files:

end2

Each file is comma-delimited when opened in a text editor:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top