将数据导出为CSV - Excel VBA

时间:2013-10-09 15:13:13

标签: excel vba csv excel-vba

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

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那样然后激活它?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:7)

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

    Pathname = "" & Thisworkbook.path & "YourName.csv"
    Sheets("Sheet you want as CSV").Move
    ActiveWorkbook.SaveAs Filename:=PathName, _
        FileFormat:=xlCSV, CreateBackup:=False

答案 2 :(得分: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

希望这有帮助