11

假设我有一个函数可以将一些数据生成到当前工作表的单元格中,例如:

Cells(1, "A").Value = ...
Cells(2, "A").Value = ...
Cells(3, "A").Value = ...
Cells(4, "A").Value = ...

我不想成为当前工作簿中的当前工作表,而是想创建并将其加载到 csv 文件中,以给定路径

C:\USERS\Documents\Sample.csv

我见过类似的东西

     ActiveWorkbook.SaveAs Filename:= _
"c:\MyFile.csv", FileFormat:=xlCSV _
, CreateBackup:=False

但这只会将当前工作簿保存到另一个位置,但我不想在当前工作表中生成数据然后保存,而是想立即导出?无论如何我可以做到这一点。也许喜欢ActiveWorkbook = //pathname然后激活它?

4

3 回答 3

12

您可以使用 VBA 非常简单地写入 CSV。一个例子可能是:

Sub WriteCSVFile()

Dim My_filenumber As Integer
Dim logSTR As String

My_filenumber = FreeFile

logSTR = logSTR & Cells(1, "A").Value & " , "
logSTR = logSTR & Cells(2, "A").Value & " , "
logSTR = logSTR & Cells(3, "A").Value & " , "
logSTR = logSTR & Cells(4, "A").Value

Open "C:\USERS\Documents\Sample.csv" For Append As #My_filenumber
    Print #My_filenumber, logSTR
Close #My_filenumber

End Sub
于 2013-10-09T16:04:20.140 回答
8

使用 .move 制作目标工作表的新书,然后将新创建的书 .save 保存为 CSV。调整路径名以调整您希望保存 csv 的目录。

    Pathname = "" & Thisworkbook.path & "YourName.csv"
    Sheets("Sheet you want as CSV").Move
    ActiveWorkbook.SaveAs Filename:=PathName, _
        FileFormat:=xlCSV, CreateBackup:=False
于 2014-08-19T15:12:55.003 回答
1

刚刚将@CharlieSmith 的代码修改为一个相当简单且更可用的代码,它将工作簿中的所有工作表转换为以各自工作表名称命名的新 csv 文件。

Sub WriteCSVFile()
Dim i As Integer
Dim WS_Count As Integer

WS_Count = ActiveWorkbook.Worksheets.Count
For i = 1 To WS_Count
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets(i)
     PathName = "" & ThisWorkbook.Path & "\" & ws.Name & ".csv"
    ws.Copy
    ActiveWorkbook.SaveAs Filename:=PathName, _
        FileFormat:=xlCSV, CreateBackup:=False
Next i

End Sub

希望这可以帮助

于 2017-04-25T14:43:56.020 回答