将工作簿中的每个工作表保存为单独的CSV文件

Ale*_*eby 75 csv excel vba

如何将每个工作表保存在Excel工作簿中以CSV使用宏分隔文件?

我有一个excel有多张表,我正在寻找一个宏,将每张表单独保存CSV (comma separated file).Excel不允许您将所有工作表保存到不同的CSV文件.

Gra*_*ham 79

@AlexDuggleby:您不需要复制工作表,可以直接保存它们.例如:

Public Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

    SaveToDirectory = "C:\"

    For Each WS In ThisWorkbook.Worksheets
        WS.SaveAs SaveToDirectory & WS.Name, xlCSV
    Next

End Sub
Run Code Online (Sandbox Code Playgroud)

只有潜在的问题是将工作簿保存为最后一个csv文件.如果您需要保留原始工作簿,则需要另存为.

  • +1要在Excel中使用,可以:Alt + F11,插入>模块,粘贴代码,单击播放按钮. (9认同)
  • 如果更改SaveToDirectory,请确保保留尾部反斜杠. (6认同)
  • 很好的答案!如果要保存到与电子表格相同的目录,可以使用`SaveToDirectory = ThisWorkbook.Path & "\"` (3认同)

小智 65

这里有一个可视文件选择器,可以选择要保存文件的文件夹,还可以选择CSV分隔符(我使用管道'|'因为我的字段包含逗号,我不想处理报价):

' ---------------------- Directory Choosing Helper Functions -----------------------
' Excel and VBA do not provide any convenient directory chooser or file chooser
' dialogs, but these functions will provide a reference to a system DLL
' with the necessary capabilities
Private Type BROWSEINFO    ' used by the function GetFolderName
    hOwner As Long
    pidlRoot As Long
    pszDisplayName As String
    lpszTitle As String
    ulFlags As Long
    lpfn As Long
    lParam As Long
    iImage As Long
End Type

Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
                                             Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
                                           Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long

Function GetFolderName(Msg As String) As String
    ' returns the name of the folder selected by the user
    Dim bInfo As BROWSEINFO, path As String, r As Long
    Dim X As Long, pos As Integer
    bInfo.pidlRoot = 0&    ' Root folder = Desktop
    If IsMissing(Msg) Then
        bInfo.lpszTitle = "Select a folder."
        ' the dialog title
    Else
        bInfo.lpszTitle = Msg    ' the dialog title
    End If
    bInfo.ulFlags = &H1    ' Type of directory to return
    X = SHBrowseForFolder(bInfo)    ' display the dialog
    ' Parse the result
    path = Space$(512)
    r = SHGetPathFromIDList(ByVal X, ByVal path)
    If r Then
        pos = InStr(path, Chr$(0))
        GetFolderName = Left(path, pos - 1)
    Else
        GetFolderName = ""
    End If
End Function
'---------------------- END Directory Chooser Helper Functions ----------------------

Public Sub DoTheExport()
    Dim FName As Variant
    Dim Sep As String
    Dim wsSheet As Worksheet
    Dim nFileNum As Integer
    Dim csvPath As String


    Sep = InputBox("Enter a single delimiter character (e.g., comma or semi-colon)", _
                   "Export To Text File")
    'csvPath = InputBox("Enter the full path to export CSV files to: ")

    csvPath = GetFolderName("Choose the folder to export CSV files to:")
    If csvPath = "" Then
        MsgBox ("You didn't choose an export directory. Nothing will be exported.")
        Exit Sub
    End If

    For Each wsSheet In Worksheets
        wsSheet.Activate
        nFileNum = FreeFile
        Open csvPath & "\" & _
             wsSheet.Name & ".csv" For Output As #nFileNum
        ExportToTextFile CStr(nFileNum), Sep, False
        Close nFileNum
    Next wsSheet

End Sub



Public Sub ExportToTextFile(nFileNum As Integer, _
                            Sep As String, SelectionOnly As Boolean)

    Dim WholeLine As String
    Dim RowNdx As Long
    Dim ColNdx As Integer
    Dim StartRow As Long
    Dim EndRow As Long
    Dim StartCol As Integer
    Dim EndCol As Integer
    Dim CellValue As String

    Application.ScreenUpdating = False
    On Error GoTo EndMacro:

    If SelectionOnly = True Then
        With Selection
            StartRow = .Cells(1).Row
            StartCol = .Cells(1).Column
            EndRow = .Cells(.Cells.Count).Row
            EndCol = .Cells(.Cells.Count).Column
        End With
    Else
        With ActiveSheet.UsedRange
            StartRow = .Cells(1).Row
            StartCol = .Cells(1).Column
            EndRow = .Cells(.Cells.Count).Row
            EndCol = .Cells(.Cells.Count).Column
        End With
    End If

    For RowNdx = StartRow To EndRow
        WholeLine = ""
        For ColNdx = StartCol To EndCol
            If Cells(RowNdx, ColNdx).Value = "" Then
                CellValue = ""
            Else
                CellValue = Cells(RowNdx, ColNdx).Value
            End If
            WholeLine = WholeLine & CellValue & Sep
        Next ColNdx
        WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
        Print #nFileNum, WholeLine
    Next RowNdx

EndMacro:
    On Error GoTo 0
    Application.ScreenUpdating = True

End Sub
Run Code Online (Sandbox Code Playgroud)

  • 当然,MacOSX上的文件选择器对话框失败. (6认同)
  • 由于问题没有要求非标准分隔符,我不清楚你为什么用单元例程编写一个单元格.如果你要沿着这条路线使用变量数组而不是范围,在引用它之前重新计算`UsedRange`(删除潜在的多余空间),将longs字符串与组合短字符串连接起来`WholeLine = WholeLine&(CellValue&Sep)`,使用字符串函数而不是变体(`Left $`not`Left`)等 (2认同)

Ale*_*eby 19

这里的解决方案应该适用于Excel> 2000,但仅在2007年进行了测试:

Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub
Run Code Online (Sandbox Code Playgroud)

(OT:我想知道是否会取代我的一些小型博客)

  • 谢谢!在Office 2010中工作.我花了一段时间才意识到不得不在文件路径中留下尾随的"/",否则会出错 (2认同)

Rob*_*rns 13

在Graham的答案的基础上,额外的代码将工作簿以原始格式保存回原始位置.

Public Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

 CurrentWorkbook = ThisWorkbook.FullName
 CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook

      SaveToDirectory = "C:\"

      For Each WS In ThisWorkbook.Worksheets
          WS.SaveAs SaveToDirectory & WS.Name, xlCSV
      Next

 Application.DisplayAlerts = False
  ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
 Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub
Run Code Online (Sandbox Code Playgroud)


Jos*_*ter 6

使用 Visual Basic 循环浏览工作表并保存.csv文件。

\n
    \n
  1. .xlsx在 Excel 中打开文件。

    \n
  2. \n
  3. option+F11

    \n
  4. \n
  5. Insert\xe2\x86\x92Module

    \n
  6. \n
  7. 将其插入模块代码中:

    \n
    Public Sub SaveWorksheetsAsCsv()\n\n Dim WS As Excel.Worksheet\n Dim SaveToDirectory As String\n\n SaveToDirectory = "./"\n\n For Each WS In ThisWorkbook.Worksheets\n    WS.SaveAs SaveToDirectory & WS.Name & ".csv", xlCSV\n Next\n\nEnd Sub\n
    Run Code Online (Sandbox Code Playgroud)\n
  8. \n
  9. 运行模块。

    \n

    (即单击顶部的播放按钮,然后单击对话框中的“运行”(如果弹出)。)

    \n
  10. \n
  11. 在 中查找您的.csv文件~/Library/Containers/com.microsoft.Excel/Data

    \n
    open ~/Library/Containers/com.microsoft.Excel/Data\n
    Run Code Online (Sandbox Code Playgroud)\n
  12. \n
  13. 关闭.xlsx文件。

    \n
  14. \n
  15. 冲洗并重复其他.xlsx文件。

    \n
  16. \n
\n