有没有办法将范围批量写入文本/CSV 文件?

Ste*_*e06 3 csv excel vba file

我习惯使用 VBA 中的 write 命令将一系列单元格的内容(值)写入文本文件,例如:

write #myfile, Range("A1").value, Range("A2).value, Range("A3).value

是否存在更优雅和方便的内置方法来将整个范围直接转储到分隔文件,甚至可能一次转储多行?或者有人提出了定制的解决方案吗?我认为这将非常有用。

Dan*_*iel 5

我写信给你,它仍然可以改进,但我认为它已经足够好了:

Sub SaveRangeAsCSV(r As Range, filename As String, overwrite As Boolean)
    Dim wB As Workbook
    Dim c As Range
    Dim usedRows As Long
    If overwrite Then
        If Dir(filename) <> "" Then Kill filename
        If Err.Number <> 0 Then
            MsgBox "Could not delete previously existing file." & vbNewLine & Err.Number & ": " & Err.Description
            Exit Sub
        End If
    End If
    If Dir(filename) <> "" Then
        Set wB = Workbooks.Open(filename)
    Else
        Set wB = Workbooks.Add
    End If

    With wB.Sheets(1)
        usedRows = .UsedRange.Rows.Count
        'Check if more than 1 row is in the used range.
        If usedRows = 1 Then
            'Since there's only 1 row, see if there's more than 1 cell.
            If .UsedRange.Cells.Count = 1 Then
                'Since there's only 1 cell, check the contents
                If .Cells(1, 1) = "" Then
                      'you're dealing with a blank workbook
                      usedRows = 0
                End If
            End If
        End If
        'Check if range is contigious
        If InStr(r.Address, ",") Then
            For Each c In r.Cells
                .Range(c.Address).Offset(usedRows, 0).Value = c.Value
            Next
        Else
            .Range(r.Address).Offset(usedRows, 0).Value = r.Value
        End If
    End With
    wB.SaveAs filename, xlCSV, , , , False
    wB.Saved = True
    wB.Close
End Sub
Sub Example()
    'I used Selection here just to make it easier to test.
    'Substitute your actual range, and actual desired filepath
    'If you pass false for overwrite, it assumes you want to append
    'It will give you a pop-up asking if you want to overwrite, which I could avoid
    'by copying the worksheet and then closing and deleting the file etc... but I
    'already spent enough time on this one.
    SaveRangeAsCSV Selection, "C:\proofOfConcept.csv", False
End Sub
Run Code Online (Sandbox Code Playgroud)

使用它时,只需提供实际范围、实际文件名以及是否要覆盖该文件。:) 这已更新为允许非连续范围。对于合并单元格,它最终会将值放入合并范围的第一个单元格中。