使用自定义分隔符将工作表压缩为CSV?

时间:2015-08-13 18:21:39

标签: excel vba csv

我需要使用工作簿中的自定义分隔符创建CSV字符串。

我编写了这个函数来完成这个技巧,但问题是循环遍历行太慢了:

Public Function CSVStringFromWB(wb As Workbook, FieldTerminator As String) As String
    Dim Line As String
    Dim r As Long
    Dim ColsCount As Long
    Dim RowsCount As Long
    ColsCount = wb.Sheets(1).UsedRange.Columns.Count
    RowsCount = wb.Sheets(1).UsedRange.Rows.Count
    With wb.Sheets(1)
        For r = 1 To RowsCount
            Line = Join(Application.Transpose(Application.Transpose(.Range(.Cells(r, 1), .Cells(r, ColsCount)).Value)), FieldTerminator)
            CSVStringFromWB = CSVStringFromWB + Line + vbNewLine
        Next r
    End With
End Function

是否有更快的替代方法可以使用自定义分隔符将范围转换为CSV字符串?

2 个答案:

答案 0 :(得分:1)

这大约快20倍(使用6k行x 20列)

Public Function FasterCSVStringFromWB(wb As Workbook, _
                                      FieldSep As String) As String
    Dim data, lines() As String, line As String, sep As String
    Dim ColsCount As Long, r As Long, c As Long
    Dim RowsCount As Long

    data = wb.Sheets(1).UsedRange.Value
    ColsCount = UBound(data, 2)
    RowsCount = UBound(data, 1)
    ReDim lines(1 To RowsCount)

    For r = 1 To RowsCount
        sep = ""
        line = ""
        For c = 1 To ColsCount
            line = line & sep & data(r, c)
            If c = 1 Then sep = FieldSep
        Next c
        lines(r) = line
    Next r

    FasterCSVStringFromWB = Join(lines, vbNewLine)
End Function

答案 1 :(得分:0)

逐个单元格读取整个excel表格单元格很慢。如果可以,将所需的excel行/列保存为单独的csv文件,然后编写一个单独的小程序,将csv中的逗号更改为其他内容。

如果你必须使用vba浏览整个excel表,那么你所做的可能是唯一的方法。

如果你需要处理大量的excel文件,请尝试复制所需的行/列,然后粘贴到新的工作表中,然后将工作表保存为csv,然后更改分隔符。