VBA导出工作表以分隔CSV,从工作表4开始

时间:2018-07-30 19:24:54

标签: excel vba excel-vba

正如标题所示,我正在尝试导出工作表(从第四个工作表开始,并且是固定值)以分隔CSV文件。理想情况下,它应该直接放在桌面上包含每个文件的文件夹中。下面是我一直在使用的代码/试图进行调整-

Sub ExportSheetsToCSV()
Dim xWs As Worksheet
Dim xcsvFile As String
For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Copy
    xcsvFile = CurDir & "\" & xWs.Name & ".csv"
    Application.ActiveWorkbook.SaveAs Filename: = xcsvFile, _
    FileFormat: = xlCSV, CreateBackup: = False
    Application.ActiveWorkbook.Saved = True
    Application.ActiveWorkbook.Close
Next

结束子

1 个答案:

答案 0 :(得分:2)

使用工作表集合索引。

Sub ExportSheetsToCSV()

    Dim xWs As Worksheet
    Dim xcsvFile As String, w as long
    For w=4 to ActiveWorkbook.Worksheets.count
        with ActiveWorkbook.Worksheets(w)
            xcsvFile = CurDir & "\" & .Name & ".csv"
            .Copy
            with ActiveWorkbook
                .SaveAs Filename:=xcsvFile, FileFormat:=xlCSV
                .Close savechanges:=false
            end with
        end with
    Next w

end sub

CurDir在这里合适吗? ActiveWorkbook.Path可能是另一个选择。