将数据导出为CSV - Excel VBA [英] Exporting Data into a CSV - Excel VBA

查看:874
本文介绍了将数据导出为CSV - Excel VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have a function that generates some data into cells into the current worksheet like :

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

而不是当前工作表当前工作簿,我想创建并将其加载到csv文件,给一个给定路径

Instead of the being the current worksheet in the current workbook, I want to create and load it into a csv file, to a give path

C:\USERS\Documents\\ \\ Sample.csv

我看过类似

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

但这只会将当前工作簿保存到另一个位置,但是我不想在当前工作表中生成数据,而是我想立即出口呢?有没有反正我可以做到。也许会使 ActiveWorkbook = // pathname 然后激活它?

But this will just save the current workbook to another location, but I don't want to generate data in the current worksheet and then save, rather I want to export right away? Is there anyway I can do that. Maybe making like ActiveWorkbook = //pathname and then Activating it ?

推荐答案

您可以使用VBA简单地写入CSV。
例如:

You can write to a CSV quite simply using VBA. An example could be:

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

这篇关于将数据导出为CSV - Excel VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆