Ник
Учитывая вы расширили на ваш вопрос с различиями, и застежка-молния часть является существенным аддон я описал решение ниже, что:
- Создает файл CSV, пропуская определенные листы используя эту строку
Case "TOC", "Lookup"
- Добавляет их в Zip-файл. Этот раздел в значительной степени опирается на Ron de Bruin's code here
код будет создавать пути под StrMain
и StrZipped
, если они уже не существует
Как ActiveWorkbook
получает подразделена на CSV-файлы тестов кода, что ActiveWorkbook
сохраняется до начала работы
В (2) Я столкнулся с проблемой, которую я видел ранее, в моем Produce an Excel list of the attributes of all MP3 files that sit in or below the "My Music" folde, где ошибка Shell.Application
при передаче строковых переменных. Поэтому я стиснул зубы и добавил жесткое кодирование предыдущих путей для Zip_All_Files_in_Folder
.Я закомментирована моей предыдущей переменной мимоходом, чтобы показать, где я попробовал этот
VBA to save CSVS
Public Sub SaveWorksheetsAsCsv()
Dim ws As Worksheet
Dim strMain As String
Dim strZipped As String
Dim strZipFile As String
Dim lngCalc As Long
strMain = "C:\csv\"
strZipped = "C:\zipcsv\"
strZipFile = "MyZip.zip"
If Not ActiveWorkbook.Saved Then
MsgBox "Pls save " & vbNewLine & ActiveWorkbook.Name & vbNewLine & "before running this code"
Exit Sub
End If
With Application
.DisplayAlerts = False
.ScreenUpdating = False
lngCalc = .Calculation
.Calculation = xlCalculationManual
End With
'make output diretcories if they don't exist
If Dir(strMain, vbDirectory) = vbNullString Then MkDir strMain
If Dir(strZipped, vbDirectory) = vbNullString Then MkDir strZipped
For Each ws In ActiveWorkbook.Worksheets
Select Case ws.Name
Case "TOC", "Lookup"
'do nothing for these sheets
Case Else
ws.SaveAs strMain & ws.Name, xlCSV
End Select
Next
'section to run the zipping
Call NewZip(strZipped & strZipFile)
Application.Wait (Now + TimeValue("0:00:01"))
Call Zip_All_Files_in_Folder '(strZipped & strZipFile, strMain)
'end of zipping section
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = lngCalc
End With
End Sub
'Create the ZIP file if it doesn't exist
Sub NewZip(sPath As String)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
' Add the files to the Zip file
Sub Zip_All_Files_in_Folder() '(sPath As String, ByVal strMain)
Dim oApp As Object
Set oApp = CreateObject("Shell.Application")
'Shell doesn't handle the variable strings in my testing. So hardcode the same paths :(
sPath = "C:\zipcsv\MyZip.zip"
strMain = "c:\csv\"
'Copy the files to the compressed folder
oApp.Namespace(sPath).CopyHere oApp.Namespace(strMain).items
MsgBox "You find the zipfile here: " & sPath
End Sub
Возможный дубликат [Макрос для сохранения каждого листа в книге Excel для разделения файлов CSV] (http://stackoverflow.com/questions/59075/macro-to-save-each-sheet-in-an-excel-workbook -to-separate-csv-files) – bernie
SO * имеет * систему бонусных очков, но вы ее не используете. Мошенник! – bzlm
Решение, представленное в аналогичном ответе, не удовлетворяет моим требованиям. Приношу свои извинения, если бы я опубликовал эту тему. –