In this article, I am going to teach you 4 VBA Methods of – how to export data from Excel Range to a CSV file format using Excel VBA.
CSV is an abbreviation of Comma Separated Value. As the name suggests, it is clear that this file stores the tabular data in a format where data is separated by comma.
Interestingly, CSV is also a plain text file type. Here each line represents a row and each value separated by comma, resides in columns.
Important Note: Since comma is used as delimiter in CSV file – so what if your data itself has comma (,) as a value? To overcome this issue, CSV file format, stores such values within double quotes (” “) and then separated by comma(,).
Let’s get started then…
Methods of Exporting Excel data to CSV Files using VBA
In this article, following are the methods which I am using to Export Excel data i CSV format.
Before we go in to details, I would like to recommend you guys to go through following tutorials – this will help you in understanding the code better –
In following tutorial about interaction with text files through Excel VBA, we have talked a lot about creating new text files, exporting data from an Excel Range to Text file and so many other different topics.
VBA Guide to Interact with Text Files – Part – 1
VBA Guide to Interact with Text Files – Part – 2
1. Export ActiveWorkSheet as CSV file
Advantages of this method
1. This is a very simple and quickest method to export your Excel data to a CSV file.
2. No extra coding required in order to maintain the comma delimiter or double quotes etc. Excel does it by itself.
At the same time, this method has some short comings or challenges as well.
Drawbacks of this Method
1. In this method, data from ActiveSheet is saved as CSV file only. It ignores rest other sheets and its data.
2. You do not have control over data – which one to be exported or ignored. It will export every single data from the sheet to CSV format.
For example: If you have some blank rows at the beginning of the sheet etc., which you do not want to save it in CSV, it is not possible to ignore them. It will still save those lines as blank values in the CSV.
Best case when it should be used?
This is the best option, when your excel sheet has, the only data which you want to export it as a CSV file. That means it does not have any other data which you want to ignore while exporting it to csv.
VBA Code
Sub saveSheetToCSV()
Dim myCSVFileName As String
Dim tempWB As Workbook
Application.DisplayAlerts = False
On Error GoTo err
myCSVFileName = ThisWorkbook.Path & "" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
ThisWorkbook.Sheets("YourSheetToCopy").Activate
ActiveSheet.Copy
Set tempWB = ActiveWorkbook
With tempWB
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
Explanation of the Code
This method is simply using the SaveAs feature of ActiveSheet to CSV format. Rest is self explanatory.
2. VBA to Export Specific Range to CSV – Method 1
Advantages of this method
This method overcomes both the challenges of the first Method.
1. Here you have full control over which all data you want to be part of your CSV file.
2. You can read data from random places and even from different sheets as well.
3. You can use your own delimiter – For example: instead of comma, you may use semicolon(;)
Drawbacks of this Method
1. The only shortcoming with this method, as compared to first method, is it has few more lines of code and execution time will be more because you are reading data for each row and column and putting them together in CSV file – separating them by comma.
Best case when it should be used?
1. When your data is scattered
2. You want to have control over data (Format check, some transformation logic etc.)
VBA Codes
Sub exportRangeToCSVFile()
Dim myCSVFileName As String
Dim myWB As Workbook
Dim rngToSave As Range
Dim fNum As Integer
Dim csvVal As String
Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
csvVal = ""
fNum = FreeFile
Set rngToSave = Range("B2:H30")
Open myCSVFileName For Output As #fNum
For i = 1 To rngToSave.Rows.Count
For j = 1 To rngToSave.Columns.Count
csvVal = csvVal & Chr(34) & rngToSave(i, j).Value & Chr(34) & ","
Next
Print #fNum, Left(csvVal, Len(csvVal) - 2)
csvVal = ""
Next
Close #fileNumber
End Sub
Explanation of above Code
In above code, I am doing the following:
1. It is a simple for loop, using which I am concatenating each row and columns data separated by comma (,)
2. Print each rows data in csv file.
3. That’s all… your csv file is ready to use
3. VBA to Export excel Range or Table to csv – Method 2
If you want a specific range or Table to be exported as CSV from a Worksheet, which has lot more other data as well that you want to ignore, then this method should be used. Most importantly data is huge and chances are that your data might have comma (,) or double quotes (” “) as part of values.
How this method works?
Step 1: Copy the Range or Table data in to a New WorkSheetat Cell A1
Step 2: Now this new Worksheet has “the only data” which you want to save as CSV, therefore, apply method 1 and saveAs this WorkSheet as CSV file.
Best case when it should be used?
1. When you have a clear range of data which you want to export as csv
2. Data is large enough.
3. When there are chances that your data might have comma or double quotes as a value
VBA Code
Sub saveRangeToCSV()
Dim myCSVFileName As String
Dim myWB As Workbook
Dim tempWB As Workbook
Dim rngToSave As Range
Application.DisplayAlerts = False
On Error GoTo err
Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
Set rngToSave = Range("C3:H50")
rngToSave.Copy
Set tempWB = Application.Workbooks.Add(1)
With tempWB
.Sheets(1).Range("A1").PasteSpecial xlPasteValues
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
VBA Code Explanation
Above VBA Code is doing the followings:
1. Copy the Range from your Excel Sheet – rngToSave
2. Create a new Excel Workbook
3. Paste the Copied range data in to the first sheet of the workbook from A1 cell – .Sheets(1).Range(“A1”).PasteSpecial xlPasteValues
4. SaveAs this new workbook as CSV file
5. You are done Now 🙂
4. VBA to Export excel Table to CSV format
This is the simplest method to save an excel table to CSV format. Most importantly – your data must NOT have comma (,) as part of values. In such case, you should use above method – 3.
VBA for saving Excel Table as CSV
Sub saveTableToCSV()
Dim tbl As ListObject
Dim csvFilePath As String
Dim fNum As Integer
Dim tblArr
Dim rowArr
Dim csvVal
Set tbl = Worksheets("YourSheetName").ListObjects("YourTableName")
csvFilePath = "C:UsersvmishraDesktopCSVFile.csv"
tblArr = tbl.DataBodyRange.Value
fNum = FreeFile()
Open csvFilePath For Output As #fNum
For i = 1 To UBound(tblArr)
rowArr = Application.Index(tblArr, i, 0)
csvVal = VBA.Join(rowArr, ",")
Print #1, csvVal
Next
Close #fNum
Set tblArr = Nothing
Set rowArr = Nothing
Set csvVal = Nothing
End Sub
Explanation about the VBA Code above
Above code is doing the following
1. Storing the whole content of your table into a two dimensional array – tblArr
2. For each row – extract the data in to one dimensional array rowArr
3. Join all the data of single dimensional array by using comma as delimiter and store it in to a variable – csvVal
4. Print this comma separated data in the csv file (which was created)
5. Repeat this process for each row of the table – For loop is used to do so
I have tried covering all possible methods to export your excel data to CSV format.
I would really appreciate, if you provide your feedback. Do let me know by writing your comment here in the comment section of this article.
Did you like this article?
Then share it with your friends… spread knowledge…Learn All about interacting with Text Files in Excel VBA like opening, creating, writing, reading etc. from Text Files using Excel VBA code
Часто при формировании прайс-листов требуется выгрузить большой объём данных в текстовый файл в формате CSV (разделитель — точка с запятой, или запятая)
И далеко не всегда может помочь сохранение файла в этом формате, поскольку в выгрузку попадают лишние данные (заголовки таблиц, лишние строки и столбцы, и т.д.)
В данном случае поможет экспорт заданного диапазона ячеек в файл CSV, что проще всего сделать макросом с использованием функции Range2CSV:
Sub ЭкспортПрайсЛистаВФорматеCSV() On Error Resume Next Dim sh As Worksheet: Set sh = ActiveSheet ' обрабатывается активный лист ' диапазон ячеек с A5 до последней заполненной ячейки в столбце A ' расширенный по горизонтали на 10 столбцов (выгружаются столбцы с A по J) Dim ra As Range: Set ra = sh.Range(sh.[A5], sh.Range("A" & sh.Rows.Count).End(xlUp)).Resize(, 10) ' формируем текстовую строку, содержащую текст диапазона в формате CSV CSVtext$ = Range2CSV(ra, ";") ' можно указать другой разделитель столбцов ' создаём в папке с файлом XLS подпапку для CSV-прайсов (если такой папки ещё нет) CSVfolder$ = ThisWorkbook.Path & "CSV prices": MkDir CSVfolder$ ' формируем имя создаваемого файла CSV (c указанием текущей даты) CSVfilename$ = Format(Now, "YYYY MM DD HH-NN-SS") & ".csv" ' сохраняем текстовую CSV-строку CSVtext$ в файл с именем CSVfilename$ SaveTXTfile CSVfolder$ & CSVfilename$, CSVtext$ End Sub
Вот код самой функции Range2CSV:
Function Range2CSV(ByRef ra As Range, Optional ByVal ColumnsSeparator$ = ";", _ Optional ByVal RowsSeparator$ = vbNewLine) As String If ra.Cells.Count = 1 Then Range2CSV = ra.Value & RowsSeparator$: Exit Function If ra.Areas.Count > 1 Then Dim ar As Range For Each ar In ra.Areas Range2CSV = Range2CSV & Range2CSV(ar, ColumnsSeparator$, RowsSeparator$) Next ar Exit Function End If arr = ra.Value buffer$ = "" ' иначе конкатенация длинных текстовых строк притормаживает макрос For i = LBound(arr, 1) To UBound(arr, 1) txt = "": For j = LBound(arr, 2) To UBound(arr, 2): txt = txt & ColumnsSeparator$ & arr(i, j): Next j Range2CSV = Range2CSV & Mid(txt, Len(ColumnsSeparator$) + 1) & RowsSeparator$ ' для многократного увеличения производительности при больших диапазонах данных If Len(Range2CSV) > 50000 Then buffer$ = buffer$ & Range2CSV : Range2CSV = "" Next i Range2CSV = buffer$ & Range2CSV End Function
Улучшенная версия кода (работает заметно быстрее), и дополнительно заключает текст всех ячеек в кавычки:
Function Range2CSV(ByRef ra As Range, Optional ByVal ColumnsSeparator$ = ";", _ Optional ByVal RowsSeparator$ = vbNewLine) As String If ra.Cells.Count = 1 Then Range2CSV = ra.Value & RowsSeparator$: Exit Function If ra.Areas.Count > 1 Then Dim ar As Range For Each ar In ra.Areas Range2CSV = Range2CSV & Range2CSV(ar, ColumnsSeparator$, RowsSeparator$) Next ar Exit Function End If arr = ra.Value ' иначе конкатенация длинных текстовых строк притормаживает макрос chr34$ = Chr(34): buffer$ = "": buffer2$ = "": Const BufferLen& = 15000 For i = LBound(arr, 1) To UBound(arr, 1) txt = "": For j = LBound(arr, 2) To UBound(arr, 2) txt = txt & ColumnsSeparator$ & chr34$ & Replace(arr(i, j), chr34$, "'") & chr34$ Next j buffer$ = buffer$ & Mid(txt, Len(ColumnsSeparator$) + 1) & RowsSeparator$ ' для многократного увеличения производительности при больших диапазонах данных If Len(buffer$) > BufferLen& Then buffer2$ = buffer2$ & buffer$: buffer$ = "" If Len(buffer2$) > BufferLen& * 40 Then _ Range2CSV = Range2CSV & buffer2$: buffer2$ = "" ': DoEvents End If Next i Range2CSV = Range2CSV & buffer2$ & buffer$ End Function
Для работы макроса понадобится ещё и функция сохранения текстового файла SaveTXTfile.
Найти её можно здесь: http://excelvba.ru/code/txt
Function SaveTXTfile(ByVal filename As String, ByVal txt As String) As Boolean On Error Resume Next: Err.Clear Set fso = CreateObject("scripting.filesystemobject") Set ts = fso.CreateTextFile(filename, True) ts.Write txt: ts.Close SaveTXTfile = Err = 0 Set ts = Nothing: Set fso = Nothing End Function
In this post I will show you how to convert an Excel file to a CSV using VBA. This post explains various techniques you can use when converting to CSV. When we convert an Excel file to CSV, we can give a preferred name of our own or we can use the original sheet name as the file name. Also it is possible to save the file to a different directory by changing the folder path. Sometimes we need to overwrite the existing files as well. So in this post you can learn how to overwrite the existing CSV file automatically overcoming the warning message.
First let’s look at the simplest case scenario. Suppose we know the absolute file path of the new file we are saving. Then we can develop the subroutine as follows.
Dim WB As Workbook
Dim FilePath As String
Set WB = ActiveWorkbook
FilePath = «D:WorkProject FilesMyFile.csv»
WB.SaveAs Filename:=FilePath, FileFormat:=xlCSV, CreateBackup:=False
End Sub
And if you have folder path in one variable and file name in another variable then you can slightly change the above subroutine like this.
Dim WB As Workbook
Dim FolderPath As String
Dim FileName As String
Set WB = ActiveWorkbook
FolderPath = «D:WorkNew Post 4»
FileName = «Test File.csv»
WB.SaveAs FileName:=FolderPath & «» & FileName, FileFormat:=xlCSV, CreateBackup:=False
End Sub
When you save the file, if the folder contains a file with the same name the Excel will display a message like this.
If you select “Yes” then it will replace the existing file with the new file. Yet sometimes you may want to overwrite the file without the user’s involvement. Fortunately there is a solution for that as well. You can use “Application.DisplayAlerts = False” to suppress that message. However, remember to set it to true after saving the file. Check below subroutine to understand how to use Application.DisplayAlerts
Dim WB As Workbook
Dim FolderPath As String
Dim FileName As String
Set WB = ActiveWorkbook
FolderPath = «D:WorkNew Post 4»
FileName = «Test File»
Application.DisplayAlerts = False
WB.SaveAs FileName:=FolderPath & «» & FileName & «.csv», FileFormat:=xlCSV, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
In the above examples we gave our own name to the CSV file. Next let’s look at how to save the
CSV file, giving sheet name as file name. To do that we need to get the file name using Activesheet.Name property. Then we can save the file using the same method.
Dim WB As Workbook
Dim FolderPath As String
Dim FileName As String
Set WB = ActiveWorkbook
FolderPath = «D:WorkNew Post 4»
FileName = ActiveSheet.Name
WB.SaveAs FileName:=FolderPath & «» & FileName & «.csv», FileFormat:=xlCSV, CreateBackup:=False
End Sub
Sometimes you may want to save the CSV file inside the same folder where the original Excel file is in. This also can be easily done with help of Workbook.Path property.
Dim WB As Workbook
Dim FolderPath As String
Dim FileName As String
Set WB = ActiveWorkbook
FolderPath = WB.Path
FileName = ActiveSheet.Name
WB.SaveAs FileName:=FolderPath & «» & FileName & «.csv», FileFormat:=xlCSV, CreateBackup:=False
End Sub
Now we learnt how to convert an Excel file to a CSV file using VBA. But what if we have more than one sheet in the Excel file. If you run above macros for an Excel file with multiple sheets, macro will convert activesheet to the CSV file. Other sheets will be deleted automatically.
Also see
How To Quote All Cells Of A CSV File
Save Each Excel Worksheet To Separate CSV File Using VBA (Worksheet Name As File Name)
I’m using Excel Tables in Excel 2010. I would like to quickly export the contents of these tables to *.csv.
My current workflow:
1. Select table manually
2. Copy the contents into a new workbook
3. Save the workbook as a *.csv file
Desired workflow:
1. Select table manually
2. Run a macro that writes to a pre-defined file name
Since the tables have unique names (e.g. CurrentDataTable), is there a function that takes the table name, target file, and desired output format and writes the output file?
asked Jan 25, 2013 at 3:57
2
There is no built-in Excel command or function that would do the kind of thing you want, but you can use VBA to program it.
The following code may be close to what you are looking for:
Sub ExportTable()
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet, wsNew As Worksheet
Dim wbNewName As String
Set wb = ThisWorkbook
Set ws = ActiveSheet
Set wbNew = Workbooks.Add
With wbNew
Set wsNew = wbNew.Sheets("Sheet1")
wbNewName = ws.ListObjects(1).Name
ws.ListObjects(1).Range.Copy
wsNew.Range("A1").PasteSpecial Paste:=xlPasteAll
.SaveAs Filename:=wb.Path & "" & wbNewName & ".csv", _
FileFormat:=xlCSVMSDOS, CreateBackup:=False
End With
End Sub
The code assumes that you have one table in each worksheet. It creates a new workbook, copies the table into Sheet 1 of that workbook, and saves the workbook as a CSV file with the same name as the table.
answered Jan 25, 2013 at 6:51
chuffchuff
3,4641 gold badge15 silver badges19 bronze badges
0
Here’s my version of chuff’s answer for Excel 2013. It also disables the modal dialogs:
Sub ExportCSV()
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet, wsNew As Worksheet
Set wb = ThisWorkbook
Set ws = ActiveSheet
Set wbNew = Workbooks.Add
Application.DisplayAlerts = False
With wbNew
Set wsNew = wbNew.Sheets("Sheet1")
ws.Rows.Copy
wsNew.Paste
.SaveAs Filename:=ws.name & ".csv", FileFormat:=xlCSV, CreateBackup:=True
wsNew.Delete
End With
Windows(ws.name & ".csv").Activate
ActiveWindow.Close
Application.DisplayAlerts = True
End Sub
answered Apr 15, 2015 at 11:28
1
I needed to do the same, but needed to specify which tables had to be exported as CSV files. I created a range named ‘ExportTables’, with the VBA as follows:
Public Sub Export()
Dim i As Integer
Dim iMax As Integer
Dim sTable As String
iMax = Range("ExportTables").Rows.Count
For i = 1 To iMax
sTable = Range("ExportTables").Cells(i, 1).Value
Call ExportTable(sTable)
Next i
End Sub
Public Sub ExportTable(tableName As String)
Dim wkb As Workbook
Dim wkbNew As Workbook
Dim wks As Worksheet
Dim wksNew As Worksheet
Set wkb = ThisWorkbook
Application.Goto Reference:=tableName
Set wks = ActiveSheet
Set wkbNew = Workbooks.Add
Set wksNew = wkbNew.Sheets(1)
wks.ListObjects(tableName).Range.Copy
wksNew.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.DisplayAlerts = False
wkbNew.SaveAs Filename:=wkb.Path & "" & tableName & ".csv", _
FileFormat:=xlCSV, CreateBackup:=False
wkbNew.Close SaveChanges:=False
Application.DisplayAlerts = True
' Release object variables.
Set wkb = Nothing
Set wkbNew = Nothing
Set wks = Nothing
Set wksNew = Nothing
End Sub
answered Jun 3, 2017 at 12:46
I was getting a 1004 error from the code above .Delete in Thorsten’s code. I merged it with this example and got this, which works for me:
Sub ExportCSV2()
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet, wsNew As Worksheet
Set wb = ThisWorkbook
Set ws = ActiveSheet
Application.DisplayAlerts = False
ws.Copy
ActiveWorkbook.SaveAs Filename:=ws.Name & ".csv", FileFormat:=xlCSV, CreateBackup:=True
Windows(ws.Name & ".csv").Activate
ActiveWorkbook.Close False
Application.DisplayAlerts = True
End Sub
Please note, this (Thorsten’s) approach exports the whole sheet, not just the table, so you get a LOT of empty rows.
answered Oct 1, 2019 at 15:09
VBA code to convert excel to csv
We can use VBA to convert and Save the Excel File as CSV file. This example macro will help us to know how to convert Excel Worksheet into a CSV Comma delimited text file. This can be used in Excel 2003,2007,2010,2013.
vba code to convert excel to csv- Syntax
Here is the example Excel VBA Syntax to convert the Excel to CSV.
Workbook.SaveAs fileName:="filepath to save the csv file", FileFormat:=xlCSV, CreateBackup:=False
VBA code to Convert and Save the Excel to CSV – Example
Here is the example macro to convert the Excel worksheet to CSV file.
'vba code to convert excel to csv Sub vba_code_to_convert_excel_to_csv() Set wb = Workbooks.Open("C:temptestwb.xlsx") wb.SaveAs fileName:="C:temptestC.csv", FileFormat:=xlCSV, CreateBackup:=False End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into CSV and Save the file with .CSV extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into CSV file.
VBA code to Convert and Save the Excel to CSV – Instructions
Please follow the below step by step instructions to test this Example VBA Macro codes:
- Step 1: Open a New Excel workbook
- Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
- Step 3: Insert a code module from then insert menu of the VBE
- Step 4: Copy the above code and paste in the code module which have inserted in the above step
- Step 5: Change the Workbook name in the code as per your example folder and also change the destination file path as per your requirement
- Step 6: Now press F5 to execute the code or F8 to debug the Macro to check it
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Related Posts
- vba code to convert excel to csv- Syntax
- VBA code to Convert and Save the Excel to CSV – Example
- VBA code to Convert and Save the Excel to CSV – Instructions
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
Introduction
This Article provides two VBA code samples to create and write to a CSV file:
1) Creating a CSV file using the Open For Output as FreeFile.
2) Creating a CSV file using the FileSystemObject object.
I prefer the latter approach mainly as I am using the FileSystemObject for further coding, for example processing all files in subfolders recursively (though that technique is not used in this article).
Creating CSV files
What’s the point?
As per
http://en.wikipedia.org/wiki/Comma-separated_values CSV is a simple file format that is widely supported, so it is often used to move tabular data between different computer programs that support the format.
For the VBA coder:
Writing to a CSV file is an efficient method to produce a report file, especially when this technique is coupled with Variant Arrays.
CSV files do not have the row limit that Excel is subject to.
The report writing is simple, each row is appended to the CSV file (using writeline or Print #), so there is no need to determine the endpoint of the report as is needed when appending VBA ranges to existing ranges.
The two code samples below use Variant Arrays to create a
transposed output (i.e. transposing columns for rows) of every WorkSheet in the ActiveWorkbook. Readers may find my Article on using Variant Arrays rather than loops useful,
Using Variant Arrays in Excel VBA for Large Scale Data Manipulation.
Understanding the Code
There are 5 major portions in the sample code:
The UsedRange of each sheet is tested. If there is no UsedRange (i.e. an empty WorkSheet) then the code skips that particular WorkSheet. If there is only a single cell then the Variant Array approach is not utilised as this approach needs a minimum of two cells to satisfy the 2D array requirement. The two IF tests are run separately to avoid test for a single cell if the sheet is already known to be blank.
The Variant Array is processed, looping through each column, row by row.
As the first value in
strTmp should not be preceded by a delimiter it is written as value only. Note that this is more efficient than testing for the first value inside the For …. Each loop.
Note that I have escaped any comma («,») values in the cells with «» as per the standard Excel treatment for CSV files.
The entire column is written to the CSV file using either
Print #lFnum, strTmp or
objTF.writeline strTmp, depending on which of the functions is used.
Using the Code
1. Copy the code at the bottom of this Article
2. Open any workbook.
3. Press Alt + F11 to open the Visual Basic Editor (VBE).
4. From the Menu, choose Insert-Module.
5. Paste the code into the right-hand code window.
6. Close the VBE, save the file if desired.
In
xl2003 go to Tools-Macro-Macros and double-click CreateCSV_Output or CreateCSV_FSO
In
xl2007 click the Macros button in the Code group of the Developer tab, then click CreateCSV_Output or CreateCSV_FSO in the list box.
Notes:
This code must be run from a regular VBA Code Module. Otherwise the code will cause an error if users try to run it from the ThisWorkbook or Sheet Code panes given the usage of Const.
It is worth noting that the ThisWorkbook and Sheet code sections should be reserved for Event coding only, «normal» VBA should be run from standard Code Modules.
Please note that for purposes of the sample code, the file path of the CSV output file is «hard-coded» as:
C:testmyfile.csv
at the top of the code. You will probably want to set the output file programmatically, for instance as a function parameter.
As mentioned earlier; For example purposes, this code
TRANSPOSES COLUMNS AND ROWS; that is, the output file contains one CSV
row for each
column in the selected range. Normally, CSV output would be row-by-row, echoing the layout visible on screen, but I wanted to demonstrate that generating the output by using VBA code provides options beyond what is available by, for instance, using the
Save As… CSV Text menu option.
Const sFilePath = "C:testmyfile.csv"
Const strDelim = ","
Sub CreateCSV_Output()
Dim ws As Worksheet
Dim rng1 As Range
Dim X
Dim lRow As Long
Dim lCol As Long
Dim strTmp As String
Dim lFnum As Long
lFnum = FreeFile
Open sFilePath For Output As lFnum
For Each ws In ActiveWorkbook.Worksheets
'test that sheet has been used
Set rng1 = ws.UsedRange
If Not rng1 Is Nothing Then
'only multi-cell ranges can be written to a 2D array
If rng1.Cells.Count > 1 Then
X = ws.UsedRange.Value2
'The code TRANSPOSES COLUMNS AND ROWS by writing strings column by column
For lCol = 1 To UBound(X, 2)
'write initial value outside the loop
strTmp = IIf(InStr(X(1, lCol), strDelim) > 0, """" & X(1, lCol) & """", X(1, lCol))
For lRow = 2 To UBound(X, 1)
'concatenate long string & (short string with short string)
strTmp = strTmp & (strDelim & IIf(InStr(X(lRow, lCol), strDelim) > 0, """" & X(lRow, lCol) & """", X(lRow, lCol)))
Next lRow
'write each line to CSV
Print #lFnum, strTmp
Next lCol
Else
Print #lFnum, IIf(InStr(ws.UsedRange.Value, strDelim) > 0, """" & ws.UsedRange.Value & """", ws.UsedRange.Value)
End If
End If
Next ws
Close lFnum
MsgBox "Done!", vbOKOnly
End Sub
Sub CreateCSV_FSO()
Dim objFSO
Dim objTF
Dim ws As Worksheet
Dim lRow As Long
Dim lCol As Long
Dim strTmp As String
Dim lFnum As Long
Set objFSO = CreateObject("scripting.filesystemobject")
Set objTF = objFSO.createtextfile(sFilePath, True, False)
For Each ws In ActiveWorkbook.Worksheets
'test that sheet has been used
Set rng1 = ws.UsedRange
If Not rng1 Is Nothing Then
'only multi-cell ranges can be written to a 2D array
If rng1.Cells.Count > 1 Then
X = ws.UsedRange.Value2
'The code TRANSPOSES COLUMNS AND ROWS by writing strings column by column
For lCol = 1 To UBound(X, 2)
'write initial value outside the loop
strTmp = IIf(InStr(X(1, lCol), strDelim) > 0, """" & X(1, lCol) & """", X(1, lCol))
For lRow = 2 To UBound(X, 1)
'concatenate long string & (short string with short string)
strTmp = strTmp & (strDelim & IIf(InStr(X(lRow, lCol), strDelim) > 0, """" & X(lRow, lCol) & """", X(lRow, lCol)))
Next lRow
'write each line to CSV
objTF.writeline strTmp
Next lCol
Else
objTF.writeline IIf(InStr(ws.UsedRange.Value, strDelim) > 0, """" & ws.UsedRange.Value & """", ws.UsedRange.Value)
End If
End If
Next ws
objTF.Close
Set objFSO = Nothing
MsgBox "Done!", vbOKOnly
End Sub
Open in new window
=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=
If you liked this article and want to see more from this author,
please click here.
If you found this article helpful, please click the Yes button near the:
Was this article helpful?
label that is just below and to the right of this text. Thanks!
=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=-=-=-
=-=-=
March 22nd, 2005
Hey, Scripting Guy! I’d like to be able to open an Excel spreadsheet, get all the information off one of the worksheets, and then save that worksheet data to a comma-separated values file. How can I do that?
— SS
Hey, SS. You know, you just have to love Excel. Yes, we know, to be “cool” these days you’re supposed to say that you don’t use Excel, that you use one of those Office wannabes instead. But we’d like to see one of those Office wannabes carry out a task like this, and in just a few lines of code to boot.
Now, to be honest, when we first read the question we weren’t sure how easy this was going to be. Turns out it was this easy:
Const xlCSV = 6 Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open("C:ScriptsTestsheet.xls") objExcel.DisplayAlerts = FALSE objExcel.Visible = TRUE Set objWorksheet = objWorkbook.Worksheets("Sheet1") objWorksheet.SaveAs "c:scriptstest.csv", xlCSV objExcel.Quit
That’s it; that’s the whole script right there. We begin by creating a constant named xlCSV and setting the value to 6; we’ll use this constant later on to specify the file format for our new file. We then create an instance of the Excel.Application object and use the Workbooks.Open method to open the spreadsheet C:ScriptsTestsheet.xls. (We also set the Visible property to TRUE, but that’s just so you can see what’s going on. If you’d prefer to have Excel run in an invisible window, then just leave this line out.)
Oh, and we have one other line of code that might be of interest:
objExcel.DisplayAlerts = FALSE
This line of code tells Excel not to display any message boxes, but to instead go with the default value any time it has a question. Why do we bother with this? Well, we’re going to save worksheet information to a CSV (comma-separated values) file. If that file already exists Excel will pop up a message box asking if we want to overwrite the existing file. For this script we’re assuming that we always want to overwrite the existing file. By setting the DisplayAlerts property to FALSE we suppress the display of that message box and tell Excel to go ahead and carry out the default operation. In this case, the default operation just happens to be, “Go ahead and overwrite any existing file.”
After we have Excel up and running it takes just two lines of code to save worksheet data to a CSV file. First, we bind to the desired worksheet (in this case, the worksheet named “Sheet1”):
Set objWorksheet = objWorkbook.Worksheets("Sheet1")
After that we simply call the SaveAs method, passing two parameters: the path to CSV file (C:ScriptsTest.csv) and the format for the new file. Because we want this saved as a CSV file, we use the xlCSV constant we defined way back when. Thus:
objWorksheet.SaveAs "c:scriptstest.csv", xlCSV
All we have to do now is call the Quit method to terminate our Excel instance and we’re done. Now try and tell us that one of those Excel wannabes is as good as the real thing!
Shameless Self-Promotion: If you’re interested in scripting Microsoft Office applications, be sure and check out the Learn about Scripting for Microsoft Office.
Vsevolod Пользователь Сообщений: 485 |
Привет Может у кого есть Макрос, который бы позволял из Excel документа сохранить нужный лист в формате CSV задав разделитель в ручную + путь для сохранения и названия файла? А то тяжко каждый раз делать
Благодарю! |
Hugo Пользователь Сообщений: 23251 |
#2 22.06.2018 10:38:50 Зачем разделитель вручную? Есть ведь стандартный «;»…
Изменено: Hugo — 22.06.2018 10:39:45 |
||
Vsevolod Пользователь Сообщений: 485 |
#3 24.06.2018 13:32:44 Hugo,
Google Контакты кушают формат с разделителем запятая:( И многие сервисы только через запятую. Еще было бы круто, если бы подсказали как вставить
Благодарю! |
||||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
Vsevolod, ещё раз прошу: не нужно писать через строку. |
Hugo Пользователь Сообщений: 23251 |
#5 24.06.2018 14:29:27 Если мне нужна запятая — я убрал бы «, local:=True»
|
||
sokol92 Пользователь Сообщений: 4445 |
#6 24.06.2018 14:43:05
При Local=False вывод не зависит от региональных настроек — разделитель полей: запятая, ограничитель полей (если необходим): двойные кавычки, разделитель дробной доли чисел: точка и т.д. Изменено: sokol92 — 24.06.2018 14:43:33 Владимир |
||
Vsevolod Пользователь Сообщений: 485 |
sokol92, Hugo, Благодарю за помощь! |
sokol92 Пользователь Сообщений: 4445 |
#8 24.06.2018 16:13:43 Часть ореола Игоря(Hugo) досталась и мне. И Вам успехов, Vsevolod! Владимир |