使用 excel-vba 将工作表范围导出到 csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45370427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:59:45  来源:igfitidea点击:

Export a worksheet range to csv using excel-vba

excel-vbavbaexcel

提问by duncan297

I am exporting from Excel to a CSV by macro using this to name the file specifically from data in the worksheet in cells in cells that will form no part of the CSV data, only the file name:

我正在通过宏从 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

However, I need to be able to limit the output to a specific range, for example cells I6 to I60, I am struggling to find a way of accomplishing this, any suggestions appreciated. TIA Duncan

但是,我需要能够将输出限制在特定范围内,例如单元格 I6 到 I60,我正在努力寻找一种方法来实现这一点,任何建议表示赞赏。蒂亚·邓肯

回答by Micha? Turczyn

One way would be concatenate values in cells (with comma between) and save it manually:

一种方法是连接单元格中的值(中间有逗号)并手动保存:

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

Here I used comma (,) as field separator and semicolon (;) as line separator, you can change it as you want. Also, set range to the one you want to save.

这里我使用逗号 (,) 作为字段分隔符,分号 (;) 作为行分隔符,您可以根据需要进行更改。此外,将范围设置为要保存的范围。

回答by avb

Here is the code to save selected range to .csv

这是将所选范围保存到 .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