How to export a range to CSV

K

krumme

Hi

I am fairly new to VBA programming, however I feel confident that
something like this should be possible.

I want to create a script that exports a range selection in Excel 2007
to a CSV file (data.csv) using comma as field separator.

I have no problem making the selection and everything, my problem is
how to get the export working with the comma separator. My Excel uses
semicolon as default!

I really hope you can help me?

Thanks!
 
D

Dave Peterson

You could create a macro that exports the data the way you want.

Here are three sites that you could steal some code from:

Earl Kiosterud's Text Write program:
www.smokeylake.com/excel
(or directly: http://www.smokeylake.com/excel/text_write_program.htm)

Chip Pearson's:
http://www.cpearson.com/excel/imptext.htm

J.E. McGimpsey's:
http://www.mcgimpsey.com/excel/textfiles.html

(or maybe you could build your own formula and copy|paste into Notepad.)

Check out Earl's Text Write program first. It may do exactly what you want
right out of the box.
 
R

Rick Rothstein

I think this code should work for you (assuming a rectangular selection),
just change the path in the Open statement to the directory location where
you want to put the Data.csv file...

Sub ExportSelectedRangeAsCSV()
Dim X As Long, FF As Long, R As Long, S() As String, StrOut As String
R = Selection.Rows.Count
ReDim S(1 To R)
For X = 1 To R
S(X) = Join(WorksheetFunction.Transpose(WorksheetFunction. _
Transpose(Selection.Rows(X).Value)), ",")
Next
StrOut = Join(S, vbNewLine)
FF = FreeFile
Open "c:\temp\Data.cvs" For Output As #FF
Print #FF, StrOut
Close #FF
End Sub
 
R

Rick Rothstein

Actually, we can save a couple of lines and two variable...

Sub ExportSelectedRangeAsCSV()
Dim X As Long, FF As Long, S() As String
ReDim S(1 To Selection.Rows.Count)
For X = 1 To Selection.Rows.Count
S(X) = Join(WorksheetFunction.Transpose(WorksheetFunction. _
Transpose(Selection.Rows(X).Value)), ",")
Next
FF = FreeFile
Open "c:\temp\Data.cvs" For Output As #FF
Print #FF, Join(S, vbNewLine)
Close #FF
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top