[英]Export a worksheet range to csv using excel-vba
我正在使用宏通過宏從Excel導出到CSV文件,以便根據工作表中單元格單元格中的數據來命名文件,而該單元格將不構成CSV數據的一部分,而僅構成文件名:
Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Dim FileName3 As String
Path = "T:\Richards Reports\MG Orders\"
FileName1 = Range("A1")
FileName2 = Range("O1")
FileName3 = Range("M1")
ActiveWorkbook.SaveAs FileName:=Path & FileName1 & "_" & FileName2 & "_" & FileName3 & ".txt", FileFormat:=xlCSV
End Sub
但是,我需要能夠將輸出限制在特定范圍內,例如I6至I60單元,我正在努力尋找一種實現此目的的方法,任何建議都值得贊賞。 TIA鄧肯
一種方法是連接單元格中的值(之間用逗號分隔)並手動保存:
Dim content As String
Dim rng As Range
Set rng = Range("A1:E2")
For Each cell In rng
content = content & "," & cell.Value
'if we go to another row insert semicolon
If cell.Column = rng.Columns.Count Then
content = content & ";"
End If
Next cell
content = Right(content, Len(content) - 1) 'remove unnecessary comma at the beginning
Set FSO = CreateObject("Scripting.FileSystemObject")
'don't forget to insert your file path here
Set wfile = FSO.CreateTextFile("YourPathHere", 2) 'connection for writing
wfile.WriteLine content
wfile.Close
在這里,我使用逗號(,)作為字段分隔符,使用分號(;)作為行分隔符,您可以根據需要進行更改。 另外,將范圍設置為要保存的范圍。
這是將所選范圍保存到.csv的代碼
Sub saveSelection2csv()
Dim range2save As Range
Dim filename As Range
Dim dataRow As Range
Dim dataRowArr() As Variant
Set filename = Worksheets("Arkusz1").Range("A1")
Open ThisWorkbook.Path & "\" & filename.Value & ".csv" For Output As #1
For Each dataRow In Selection.Rows
dataRowArr = dataRow.Value
dataRowArr = Application.Transpose(Application.Transpose(dataRowArr))
Print #1, Join(dataRowArr, ",")
Next
Close #1
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.