【问题标题】:VBA create csv filesVBA 创建 csv 文件
【发布时间】:2019-03-25 23:20:39
【问题描述】:

将批处理文件从 excel 保存为 csv。

VBA 在每 833 行之后将一张 Excel 数据表分成单独的文件。

现在我需要这些文件是 csvs 而不是 Excels。如何直接保存到 .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

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

【问题讨论】:

  • 为什么不尝试在将文件保存为 CSV 时录制宏,然后根据此调整您的代码?

标签: excel vba csv


【解决方案1】:

这样的?

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

【讨论】:

    【解决方案2】:

    假设:

    strPath = 目标文件夹的路径

    autoIncrement = 每次循环递增的变量(这样我们就可以区分文件名)

    strRow = 代表 CSV 中 1 行的字符串;连接每个 Excel 行的所有列,用分隔符 (",") 交替值


    您可以在循环中输出 CSV:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多