Marat_Mamedov Пользователь Сообщений: 213 |
#1 19.10.2016 16:49:17 Помогите пожалуйста настроить через макрос сохранения файлов в сsv я использовал стандартный мастер записи макросов и у меня получилось следующее
Помогите его сделать универсальным |
||
Ігор Гончаренко Пользователь Сообщений: 13746 |
#2 19.10.2016 16:57:43
Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
Udik Пользователь Сообщений: 372 excel 2016х64 Контакты в профиле |
#3 19.10.2016 17:12:57 или так
Изменено: Udik — 19.10.2016 17:13:35 Арфы — нет, возьмите бубен. |
||
Спасибо большое !!!! то что нужно |
|
Jesprit Пользователь Сообщений: 54 |
#5 18.11.2016 07:31:01 Использую excel 2010 Вот этот работает почти как надо, но только не для всех файлов:
Помогите изменить его для работы со всеми файлами. Изменено: Jesprit — 18.11.2016 07:33:39 |
||
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
#6 18.11.2016 11:37:19
<#0> |
||
Hugo Пользователь Сообщений: 23252 |
Jesprit, ThisWorkbook — это та КНИГА, где расположен ЭТОТ код. Изменено: Hugo — 18.11.2016 14:21:01 |
Jesprit Пользователь Сообщений: 54 |
JayBhagavan, а как бы модифицировать макрос и получить возможность выбора папки для сохранения. поискать , но не могу осилить как такое встроить в этот макрос. |
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
#9 21.11.2016 14:03:21 Jesprit, пожалуйста.
<#0> |
||
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
Часто при формировании прайс-листов требуется выгрузить большой объём данных в текстовый файл в формате 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 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. Показов 19399. Ответов 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 |