Vba excel сохранить файл как csv

 

Vsevolod

Пользователь

Сообщений: 485
Регистрация: 31.03.2016

Привет

Может у кого есть Макрос, который бы позволял из Excel документа сохранить нужный лист в формате CSV задав разделитель в ручную + путь для сохранения и названия файла?  А то тяжко каждый раз делать

  1. Move or Copy листа в новую книгу
  2. Сохранять в CSV
  3. Заходить в текстовом редакторе и менять стандартный разделитель на нужный

Благодарю!  

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#2

22.06.2018 10:38:50

Зачем разделитель вручную? Есть ведь стандартный «;»…
Ну а как задавать путь — много примеров на форуме, можете внедрить любой вот в такой свеженький код:

Код
Sub Макрос1()
'
' Макрос1 Макрос
'

'
    Application.DisplayAlerts = False
    Sheets("Расчет").Copy
    ActiveWorkbook.SaveAs Filename:="C:UsersIgorDownloadsКнига1.csv", _
                          FileFormat:=xlCSV, CreateBackup:=False, local:=True
    ActiveWindow.Close
    Application.DisplayAlerts = True
End Sub

Изменено: Hugo22.06.2018 10:39:45

 

Vsevolod

Пользователь

Сообщений: 485
Регистрация: 31.03.2016

#3

24.06.2018 13:32:44

Hugo,

Цитата
Hugo написал:
Есть ведь стандартный «;»…

Google Контакты кушают формат с разделителем запятая:( И многие сервисы только через запятую.
Сможете пожалуйста подсказать, как разделитель поменять в этом макрос?

Еще было бы круто, если бы подсказали как вставить

Код
Filename:="C:UsersIgorDownloadsКнига1_ДАТА(ДЕНЬМЕСЯЯЦГОД(2)-ВРЕМЯ(ЧАСМИНУТЫСЕКУНДЫ) в формате 240618-101116.csv"

Благодарю!

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Vsevolod, ещё раз прошу: не нужно писать через строку.

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#5

24.06.2018 14:29:27

Если мне нужна запятая — я убрал бы «, local:=True»
Но у меня запятая = десятичная запятая, как у Вас — то есть тайна великая :)
Если так уж нужно вручную — можно пробовать затем открыть текст и заменить влом одно на другое, но есть риск накосячить в текстовых строках «ячеек», где оно не нужно менять.
По сохранению:

Код
Filename:= "C:UsersIgorDownloadsКнига1_" & Format(Now, "DDMMYY-hhmmss") & ".csv"
 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

#6

24.06.2018 14:43:05

Цитата
Hugo написал:
как у Вас — то есть тайна великая

При Local=False вывод не зависит от региональных настроек —  разделитель полей: запятая, ограничитель полей (если необходим): двойные кавычки, разделитель дробной доли чисел: точка и т.д.

Изменено: sokol9224.06.2018 14:43:33

Владимир

 

Vsevolod

Пользователь

Сообщений: 485
Регистрация: 31.03.2016

sokol92, Hugo,
Крутяк! Все получилось.

Благодарю за помощь!  

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

#8

24.06.2018 16:13:43

Часть ореола Игоря(Hugo) досталась и мне. :D   И Вам успехов, 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

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

у меня их много
я их последовательно открываю, обрабатываю и мне нужно сохранять их в ту же папку под тем же именем, но с расширением .csv
вот так пробовала

Visual Basic
1
2
book.SaveAs FileFormat:=xlCSV 
book.SaveAs (Replace(XLS.Name, ".xls", ".csv", , , vbTextCompare))

все неправильно
а как, не подскажете?

заранее спасибо



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

Это записал макрорекордер:

Visual Basic
1
2
3
   ActiveWorkbook.SaveAs Filename:= _
        "C:Book1.csv", FileFormat _
        :=xlCSVMSDOS, CreateBackup:=False

Имейте ввиду, что в csv (comma separated value) формате идут только одностраничные книги. При этом теряется форматирование и еще много чего.

Боясь повториться, спрошу: «что мешает включить макрорекордер, а потом запустить полученный результат в уже написанном цикле?»

vladconn



0



1 / 1 / 1

Регистрация: 10.04.2011

Сообщений: 415

16.02.2012, 13:18

5

Цитата
Сообщение от Yulia_286

не знаю, но, вероятно, объективные обстоятельства
как вы думаете? или вы не умеете этого делать?

Меня в МВТУ учили не запоминать все наизусть, а знать, где найти ответ на возникающий вопрос. Да, я ни разу не сохранял кучу файлов экселя в .csv, но я знаю, что такого типа операцию можно записать (Сервис/Макрос/Начать запись…), потом посмотреть результат и спокойно использовать готовый код.



0



Letter_D

1 / 1 / 1

Регистрация: 18.06.2008

Сообщений: 329

16.02.2012, 13:18

6

Читайте вопрос внимательнее, товарищи.
Ей нужно в ту же папку, с тем же именем. Заранее неизвестными.
Т.е. надо подцеплять Application.Path и Application.Name
А макрорекордер этого не напишет.
Типа так надо:

Visual Basic
1
2
3
ActiveWorkbook.SaveAs _
Filename:=ActiveWorkbook.Path & "" & Replace(ActiveWorkbook.Name, ".xls", ".csv", , , vbTextCompare), _
FileFormat:=xlCSV

Но у меня при сохранении из VBA, а не ручками, почему-то сохраняется с разделителями — запятыми, а не точка с запятой.
(
Надо покопаться.



0



1 / 1 / 1

Регистрация: 10.04.2011

Сообщений: 415

16.02.2012, 13:48

7

Цитата
Сообщение от Letter_D

Читайте вопрос внимательнее, товарищи.

Сам такой :-)
Я написал: [italic]запустить полученный результат в уже написанном цикле[/italic], то есть девушка уже грамотно выполнила преобразование расширения с .xls в .csv и написала цикл обработки всех файлов.
Кстати, столь грамотное использование VBA и удержало от подробного ответа — имхо тут просто было неверное понимание того, что банальной заменой расширения невозможно заставить эксель сохранять файл в нужном формате, требуется еще указать FileFormat:==xlCSVMSDOS.



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

всем привет
не ожидала откликов в таком масштабе))
то, что мне нужно, правда, нельзя подсмотреть в коде, записанном макрорекодером
иначе я бы не спрашивала
но всем спасибо

с запятыми — это для меня не проблема

я сама вечером додумала
могу выложить, посмотрите, что получилось
берет из одной папки, обрабатывает, кладет туда же в формате .csv, все сохраняет и закрывает без всплывающих окон

Visual Basic
1
2
3
4
5
6
7
8
9
Sub DemoOpenTextFile()
For Each XLS In CreateObject("scripting.FileSystemObject").GetFolder("C:    esting").Files
Set book = Application.Workbooks.Open(XLS.Name)
'тут обработка
book.SaveAs FileName:=Replace(XLS.Name, ".xls", ".csv", , , vbTextCompare), FileFormat:=xlCSV, CreateBackup:=False
book.Saved = True
book.Close
Next XLS
End Sub



0



5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

16.02.2012, 21:12

11

Yulia_286,

1. У меня нужно вместо XLS.Name XLS.Path, сверьте.
2. Ваш цикл без нужды обрабатывает и новорожденные csv файлы, раз они в той же папке.
3. Вы забыли показать декларации ваших XLS и book.
4 Вы уверены, что не создаете scripting.FileSystemObject столько раз, сколько файлов в папке?

vladconn



0



0 / 0 / 0

Регистрация: 15.02.2012

Сообщений: 9

17.02.2012, 17:29

 [ТС]

12

2. я сама боялась, что будет такая бесконечность, но он не берет csv почему-то, к счастью, хотя, по идее, должен?
3. а я не знаю, что такое декларация и для чего это?
4. не уверена, а чем это чревато?

я вообще-то занимаюсь VBA дней 10 всего, поэтому, извините, не знаю многих, очевидных для Вас вещей

буду благодарна за ответы



0



5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

17.02.2012, 22:39

13

Yulia_286

2. Ваш цикл рассматривает все файлы, включая и новые. Вставьте If … = «.xls» …

3. Декларация (пример):
Dim objExcel as Excel.Application
Dim intIndex as Integer

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

Если уж выкладываете коды, то делайте это без ошибок!!!

Visual Basic
1
2
3
4
5
6
7
8
9
Sub DemoOpenTextFile()
For Each XLS In CreateObject("scripting.FileSystemObject").GetFolder("C:esting").Files
Set book = Application.Workbooks.Open(XLS)
'тут обработка
book.SaveAs FileName:=Replace(XLS, ".xls", ".csv", , , vbTextCompare), FileFormat:=xlCSVMSDOS, CreateBackup:=False, Local:=True
book.Saved = True
book.Close (False)
Next XLS
End Sub

Вот так все работает)))

Найдете 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.

Sub ConvertToCSV()

     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.

Sub ConvertToCSV()

     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.

Warning message when try to save with existing file name

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

Sub ConvertToCSV()

     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.

Sub ConvertToCSV()

     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.

Sub ConvertToCSV_Ex5()

     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

Понравилась статья? Поделить с друзьями:
  • Vba excel статические переменные
  • Vba excel статические массивы
  • Vba excel стандартные функции
  • Vba excel ссылки на файл
  • Vba excel ссылка на ячейку в другой книге