2016-11-16 66 views
0

我有excel列中的數據,我想提取前7列並將其保存在另一個csv文件中。文件名將採用特定的格式,基於我使用表單和其他細節(如時間戳)從用戶收集的信息。如何將Excel中的給定範圍保存爲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(我不想關閉)。

+0

提示拿起文件夾中使用文件時間戳:不是'如果.Show <> -1,則跳轉NextCode',你可以做'If .Show = -1然後退出Sub'並避免'GoTo'和行標籤。 –

回答

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-連接:

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

+0

如何使用我在表單和時間戳中從用戶收集的信息來命名文件並將csv保存在選擇的文件夾中? –