如何将每个单独的excel行导出到其自己的单独的csv文件?

时间:2019-03-27 14:00:07

标签: excel vba csv export-to-csv

我正在尝试在Adobe Illustrator中构建可变数据报告。此报告将在excel / csv文件中列出每个人的图表和数据。为了能够生成图,需要一个.csv文件,该文件的数据仅与与该特定个人相关的图有关。

例如,我有三个人:约翰,乔和安。

每个人都将有一个显示他们的交流增长的条形图,并且还将有一个显示其信心增长的图。

每个人的两个图都需要一个csv。这意味着我总共需要6个csv文件才能开始在excel中构建变量数据报告。

显然,所有数据都将放在一个excel文件中,我需要将其分开并另存为单独的csv文件。

我是否可以使用一个脚本来导出每一行(代表该行),因为它是自己的独立csv文件,并根据单元格A2和B1中的数据进行命名?

我进行了一些研究,发现一些解决方案仅引用列或如何导出选定的行,但是我将需要对100多个个人执行此操作,而这些解决方案将不适用于我需要它们的数量。我对VBA编码有些熟悉,但是我很难找到任何可以解决此问题的方法。

所以,如果我的细胞看起来像这样:

    A       B               C
1   Name    Communication   Communication End
2   John    20              25
3   Joe     16              18
4   Ann     23              27

我的文件名将如下所示: John_Communication.csv,Joe_Communication.csv,Ann_Communication.csv

并且仅将每行的数据作为自己的csv文件导出,以便我可以将数据导入Adobe Illustrator来创建个人报告所需的图形吗?

1 个答案:

答案 0 :(得分:0)

一种解决方法是从VBA宏中写出csv文件:

Sub SaveRowsToSeparateCsv()

    Dim h As Range       ' header
    Dim d As Range       ' data
    Dim r As Range       ' row
    Dim c As Range       ' cell

    Dim i As Long

    Dim ha2d As Variant  ' header 2d array
    Dim ha1d As Variant  ' header 1d array
    Dim hcsv As String   ' header in csv format

    Dim da2d As Variant  ' data 2d array
    Dim da1d As Variant  ' data 1d array
    Dim dcsv As String   ' data in csv format

    ' init ranges with header and data
    With [a1].CurrentRegion
        Set h = .Rows(1)
        Set d = .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count)
    End With

    ' we'll need header multiple times, so lets prepare it
    ha2d = h.Value
    ReDim ha1d(LBound(ha2d, 2) To UBound(ha2d, 2))
    For i = LBound(ha1d) To UBound(ha1d)
        ha1d(i) = ha2d(1, i)
    Next
    hcsv = Join(ha1d, ",") & vbNewLine

    ' now lets go through each row and save it seaprately as a csv
    For Each r In d.Rows
        da2d = r.Value
        ReDim da1d(LBound(da2d, 2) To UBound(da2d, 2))
        For i = LBound(da1d) To UBound(da1d)
            da1d(i) = da2d(1, i)
        Next
        dcsv = hcsv & Join(da1d, ",") & vbNewLine

        saveFile ThisWorkbook.Path & Application.PathSeparator _
                 & r.Cells(1) & "_Communication.csv", dcsv
    Next r

End Sub

Sub saveFile(pathname As String, sText As String)
    Dim fNum As Integer: fNum = FreeFile
    Open pathname For Output As fNum
    Print #fNum, sText;
    Close #fNum
End Sub