How to create a separate CSV file from VBA?

前端 未结 3 1248
独厮守ぢ
独厮守ぢ 2020-12-01 18:29

I need to output some results as a .csv file, that gets parsed later on by another process. In order to produce these results, I have a huge workbook containing

相关标签:
3条回答
  • 2020-12-01 19:22

    You may write a macro like to save the current workbook (opened excel file) in CSV from VBA:

    ActiveWorkbook.SaveAs Filename:="C:\Book1.csv", _
        FileFormat:=xlCSVMSDOS, CreateBackup:=False
    
    0 讨论(0)
  • 2020-12-01 19:32

    Tony's answer generally works but doesn't handle the case where your text contains commas or quotes. You may prefer to use Workbook.SaveAs method.

    Here is an example if you want to save the content of the Sheet1 as a separated csv file.

    Sub create_csv()
        Dim FileName As String
        Dim PathName As String
        Dim ws As Worksheet
    
        Set ws = ActiveWorkbook.Sheets("Sheet1")
        FileName = "filename.csv"
        PathName = Application.ActiveWorkbook.Path
        ws.Copy
        ActiveWorkbook.SaveAs FileName:=PathName & "\" & FileName, _
            FileFormat:=xlCSV, CreateBackup:=False
    End Sub
    

    Imagine that your Sheet1 contains :

    lorem ipsum

    lore,m ips"um"

    The output csv file will be :

    lorem,ipsum

    "lore,m","ips""um"""

    0 讨论(0)
  • 2020-12-01 19:34

    Is something like this what you want?

    Option Explicit
    Sub WriteFile()
    
      Dim ColNum As Integer
      Dim Line As String
      Dim LineValues() As Variant
      Dim OutputFileNum As Integer
      Dim PathName As String
      Dim RowNum As Integer
      Dim SheetValues() As Variant
    
      PathName = Application.ActiveWorkbook.Path
      OutputFileNum = FreeFile
    
      Open PathName & "\Test.csv" For Output Lock Write As #OutputFileNum
    
      Print #OutputFileNum, "Field1" & "," & "Field2"
    
      SheetValues = Sheets("Sheet1").Range("A1:H9").Value
      ReDim LineValues(1 To 8)
    
      For RowNum = 1 To 9
        For ColNum = 1 To 8
          LineValues(ColNum) = SheetValues(RowNum, ColNum)
        Next
        Line = Join(LineValues, ",")
        Print #OutputFileNum, Line
      Next
    
      Close OutputFileNum
    
    End Sub
    

    Don't forget you will need to put quotes around any field containing a comma.

    0 讨论(0)
提交回复
热议问题