如何将Excel中的给定范围保存为csv?
问题描述:
我有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(我不想关闭)。
答
这是一个相当有趣的方法。也许不太实际,我也怀疑这对于大量数据来说相当缓慢。
但是:如果您在例程的其他部分使用记录集,这可能值得深入研究。
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保存在选择的文件夹中? –
提示拿起文件夹中使用文件时间戳:不是'如果.Show -1,则跳转NextCode',你可以做'If .Show = -1然后退出Sub'并避免'GoTo'和行标签。 –