如何在excel中保存给定范围作为csv?

时间:2016-11-16 15:13:06

标签: excel vba excel-vba

我在excel列中有数据,我想提取前7列并将其保存在另一个csv文件中。文件名将以特定格式为基础,使用表格和其他详细信息(如时间戳)从用户处收集信息。

我使用以下代码:

With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = "" '<~~ The start folder path for the file picker.
    If .Show <> -1 Then GoTo NextCode
    MyPath = .SelectedItems(1) & "\"
End With

NextCode:

    With ActiveWorkbook
        .SaveAs Filename:=MyPath & MyFileName, FileFormat:=xlCSV, CreateBackup:=False
        Application.DisplayAlerts = False
        ThisWorkbook.CheckCompatibility = False
       .Close False
    End With

但这会写出输出CSV中的所有列,并关闭打开的xls(我不想关闭)。

1 个答案:

答案 0 :(得分:0)

这是一种相当有趣的方法。也许不太实际,我也怀疑这对于大量数据而言相当缓慢。

但是:如果您在日常工作的其他部分使用记录集,这可能值得研究。

Option Explicit

Sub ExportRange()

    Dim mytxt As String
    Dim fld As Object

    With GetRecordset(ThisWorkbook.Sheets(2).UsedRange)

        For Each fld In .Fields
            mytxt = mytxt & fld.Name & ";"
        Next fld

        mytxt = mytxt & vbNewLine

        While Not .EOF
            For Each fld In .Fields
                mytxt = mytxt & fld.Value & ";"
            Next fld
            mytxt = mytxt & vbNewLine
            .movenext
        Wend

        Debug.Print mytxt

    End With

    Open ThisWorkbook.Path & "\test.csv" For Binary Access Write As #1
        Put #1, , mytxt
    Close #1

End Sub

它利用此函数将范围(在我的示例中为.UsedRange)读入记录集,而无需定义ADODB引用和设置DB-Connection:

Function GetRecordset(rng As Range) As Object
    'https://usefulgyaan.wordpress.com/2013/07/11/vba-trick-of-the-week-range-to-recordset-without-making-connection/

    Dim xlXML As Object
    Dim rst As Object

    Set rst = CreateObject("ADODB.Recordset")
    Set xlXML = CreateObject("MSXML2.DOMDocument")
    xlXML.LoadXML rng.Value(xlRangeValueMSPersistXML)

    rst.Open xlXML
    Set GetRecordset = rst
End Function

编辑:

Open ThisWorkbook.Path & "\test.csv" For Binary Access Write As #1创建文件(如果它不存在)并打开它。

显然,你可以使用类似的东西 MyPath & "\test' & format(now, "yyyymmdd_hhmmss") & ".csv" 而是在使用FolderPicker

选择的文件夹中使用带时间戳的文件