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! Владимир |
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
Yulia_286 0 / 0 / 0 Регистрация: 15.02.2012 Сообщений: 9 |
||||
1 |
||||
15.02.2012, 12:28. Показов 19397. Ответов 13 Метки нет (Все метки)
у меня их много
все неправильно заранее спасибо
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
15.02.2012, 15:20 |
2 |
Не знаю, но что мешает включить макрорекордер, а потом запустить полученный результат в уже написанном цикле?
0 |
0 / 0 / 0 Регистрация: 15.02.2012 Сообщений: 9 |
|
15.02.2012, 18:26 [ТС] |
3 |
не знаю, но, вероятно, объективные обстоятельства
0 |
VladConn 5 / 5 / 3 Регистрация: 17.10.2007 Сообщений: 1,119 |
||||
15.02.2012, 20:36 |
4 |
|||
Yulia_286 Это записал макрорекордер:
Имейте ввиду, что в csv (comma separated value) формате идут только одностраничные книги. При этом теряется форматирование и еще много чего. Боясь повториться, спрошу: «что мешает включить макрорекордер, а потом запустить полученный результат в уже написанном цикле?» vladconn
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
16.02.2012, 13:18 |
5 |
не знаю, но, вероятно, объективные обстоятельства Меня в МВТУ учили не запоминать все наизусть, а знать, где найти ответ на возникающий вопрос. Да, я ни разу не сохранял кучу файлов экселя в .csv, но я знаю, что такого типа операцию можно записать (Сервис/Макрос/Начать запись…), потом посмотреть результат и спокойно использовать готовый код.
0 |
Letter_D 1 / 1 / 1 Регистрация: 18.06.2008 Сообщений: 329 |
||||
16.02.2012, 13:18 |
6 |
|||
Читайте вопрос внимательнее, товарищи.
Но у меня при сохранении из VBA, а не ручками, почему-то сохраняется с разделителями — запятыми, а не точка с запятой.
0 |
1 / 1 / 1 Регистрация: 10.04.2011 Сообщений: 415 |
|
16.02.2012, 13:48 |
7 |
Читайте вопрос внимательнее, товарищи. Сам такой
0 |
5 / 5 / 3 Регистрация: 17.10.2007 Сообщений: 1,119 |
|
16.02.2012, 14:09 |
8 |
Letter_D, Я не считаю, что обязан читать вопрос еще более внимательно. Это обязанность спрашивающего формулировать вопрос в ясном и простом виде. Когда на попытку выяснить детали для пользы же страждущего начинается заигрывание, а не разъяснение этих деталей, то и нечего ожидать. Что касается запятых, а не точек с запятыми, так уже объяснил: csv означает comma separated value (значения разделенные запятыми). Согласен с Johny Walker: спрашивaющий не понимал того, что если блондинку перекрасить, то она от этого не поумнеет. vladconn
0 |
1 / 1 / 1 Регистрация: 18.06.2008 Сообщений: 329 |
|
16.02.2012, 15:46 |
9 |
Ишь какие! А xlCSVMSDOS вообще означает сохранение в dos-формате, очень приятному для юзера. Што такое «csv» — оно понятно (оно и в диалоге сохранения написано, гы), я говорил про другое: Во как. Что-то с нацнастройками или локальной версией, имхо.
0 |
Yulia_286 0 / 0 / 0 Регистрация: 15.02.2012 Сообщений: 9 |
||||
16.02.2012, 18:02 [ТС] |
10 |
|||
всем привет с запятыми — это для меня не проблема я сама вечером додумала
0 |
5 / 5 / 3 Регистрация: 17.10.2007 Сообщений: 1,119 |
|
16.02.2012, 21:12 |
11 |
Yulia_286, 1. У меня нужно вместо XLS.Name XLS.Path, сверьте. vladconn
0 |
0 / 0 / 0 Регистрация: 15.02.2012 Сообщений: 9 |
|
17.02.2012, 17:29 [ТС] |
12 |
2. я сама боялась, что будет такая бесконечность, но он не берет csv почему-то, к счастью, хотя, по идее, должен? я вообще-то занимаюсь VBA дней 10 всего, поэтому, извините, не знаю многих, очевидных для Вас вещей буду благодарна за ответы
0 |
5 / 5 / 3 Регистрация: 17.10.2007 Сообщений: 1,119 |
|
17.02.2012, 22:39 |
13 |
Yulia_286 2. Ваш цикл рассматривает все файлы, включая и новые. Вставьте If … = «.xls» … 3. Декларация (пример): 4. Это чревато поеданием памяти 5. vbBinaryCompare может быть быстрей vbTextCompare. Можете проверить, но это не очень важно. 6. Replace заменит .xls даже если это часть имени, а не расширение, и не возьмет .XLS, .Xls и так далее. Посмотрите методы FileSystemObject для этого. Тоже верно и для … & «» & … — что, если «» последняя часть Path? Вдруг это зависит от каких-то локальных настроек? FileSystemObject должен иметь подходящие методы. Успехов vladconn
0 |
Natmed80 0 / 0 / 0 Регистрация: 30.10.2009 Сообщений: 1 |
||||
10.04.2014, 15:16 |
14 |
|||
Если уж выкладываете коды, то делайте это без ошибок!!!
Вот так все работает))) Найдете 10 отличий
0 |
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)
In this guide, we’re going to show you how to save each sheet as CSV in Excel.
Download Workbook
Excel to CSV
Saving an Excel worksheet as a CSV file is an easy task. All you need to do is to use Save As section in File menu and select the CSV as the file type.
This action allows you to save the active worksheet as a CSV file. The downside of this approach is repetitiveness. You need to save as each worksheet manually.
Although a CSV file cannot preserve colors, formatting options or other stuff, Excel keeps them in the opened workbook as long as it remains open. Thus you can always save as an Excel file after creating CSV files.
The workaround is to use VBA to save each sheet as CSV like any other repetitive job in Excel. You can either record a macro while you are saving a worksheet as CSV and create a loop to repeat for each worksheet or use the following code.
VBA code for saving each sheet as CSV
Sub SaveAsCSV() Application.ScreenUpdating = False Dim wb As Workbook Dim ws As Worksheet Dim wbNew As Workbook Dim fullPath As String Dim counter As Integer Set wb = ActiveWorkbook ' loop through each worksheet For Each ws In wb.Worksheets ' run code only for visible sheets If ws.Visible = xlSheetVisible Then ' copy the worksheet to a new workbook ws.Copy ' select the new workbook Set wbNew = ActiveWorkbook ' generate a full path for the new file including CSV extension fullPath = wb.Path & "" & _ Left(wb.Name, InStrRev(wb.Name, ".") - 1) & _ "_" & ws.Name & ".csv" ' disable alerts in case of overwrite confirmation Application.DisplayAlerts = False ' save the new workbook as a CSV wbNew.SaveAs Filename:=fullPath, FileFormat:=xlCSV ' re-activate alerts Application.DisplayAlerts = True ' close the new workbook wbNew.Close SaveChanges:=False ' increase counter for the information message counter = counter + 1 End If Next ws ' pop an information message MsgBox counter _ & IIf(counter > 1, " worksheets", " worksheets") _ & " exported.", vbInformation, "Export Worksheets" Application.ScreenUpdating = True End Sub