我正在通过宏从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 邓肯
答案 0 :(得分:0)
一种方法是在单元格中连接值(用逗号表示)并手动保存:
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
这里我使用逗号(,)作为字段分隔符和分号(;)作为行分隔符,您可以根据需要更改它。另外,将范围设置为您要保存的范围。
答案 1 :(得分:0)
以下是将所选范围保存到.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