VBA创建CSV文件

时间:2019-03-25 14:52:52

标签: excel vba csv

从Excel将批处理文件另存为csv。

在第833行之后,VBA将一张Excel数据表分离为单独的文件。

现在我需要这些文件为csvs而不是Excel。如何直接保存到.csv(以逗号分隔)文件中?

我已经制作了适当的VBA以保存到Excel(xml),而不是csvs。我需要CSV。

Sub Macro1()
Dim rLastCell As Range
Dim rCells As Range
Dim strName As String
Dim lLoop As Long, lCopy As Long
Dim wbNew As Workbook

    With ThisWorkbook.Sheets(1)
    Set rLastCell = .Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious)

        For lLoop = 1 To rLastCell.Row Step 833
        lCopy = lCopy + 1
            Set wbNew = Workbooks.Add
                .Range(.Cells(lLoop, 1), .Cells(lLoop + 833, .Columns.Count)).EntireRow.Copy _
                    Destination:=wbNew.Sheets(1).Range("A1")
            wbNew.Close SaveChanges:=True, Filename:="Chunk" & lCopy & "Rows" & lLoop & "-" & lLoop + 833
        Next lLoop
    End With


End Sub

实际结果:Excel 预期结果:CSV文件

2 个答案:

答案 0 :(得分:0)

像这样吗?

Sub CSVQuotes()

Dim SrcRange As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSeparator As String
Dim FileName As Variant
Dim current As String    

FileName = Application.GetSaveAsFilename()
ListSeparator = ";"

Set SrcRange = Sheets("DATI").UsedRange

Open FileName For Output As #1
For Each CurrRow In SrcRange.Rows
    CurrTextStr = ""

    For Each CurrCell In CurrRow.Cells
        current = CurrCell

        CurrTextStr = CurrTextStr & """" & current & """" & ListSeparator
    Next
    While Right(CurrTextStr, 1) = ListSeparator
        CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
    Wend
    Print #1, CurrTextStr
    Next
Close #1

答案 1 :(得分:0)

假设:

strPath =目标文件夹的路径

autoIncrement =用于增加每个循环的变量(以便我们区分文件名)

strRow =表示CSV中1行的字符串;连接每个Excel行的所有列,并用分隔符(“,”)替换值


您可以在循环中与此一起输出CSV:

Open strPath & "\file-" & autoIncrement & ".csv" For Output As #fileNumber
Print #fileNumber, strRow
Close #fileNumber