我需要输出一些结果作为.csv
文件,稍后由另一个进程解析。为了产生这些结果,我有一个庞大的工作簿,其中包含我需要的所有宏和函数。
.csv
“创建”单独的VBA
文件? VBA
功能写入其中而不是仅仅使用“原始文本”方法进行编写?谢谢:)
答案 0 :(得分:24)
这是你想要的吗?
Option Explicit
Sub WriteFile()
Dim ColNum As Integer
Dim Line As String
Dim LineValues() As Variant
Dim OutputFileNum As Integer
Dim PathName As String
Dim RowNum As Integer
Dim SheetValues() As Variant
PathName = Application.ActiveWorkbook.Path
OutputFileNum = FreeFile
Open PathName & "\Test.csv" For Output Lock Write As #OutputFileNum
Print #OutputFileNum, "Field1" & "," & "Field2"
SheetValues = Sheets("Sheet1").Range("A1:H9").Value
ReDim LineValues(1 To 8)
For RowNum = 1 To 9
For ColNum = 1 To 8
LineValues(ColNum) = SheetValues(RowNum, ColNum)
Next
Line = Join(LineValues, ",")
Print #OutputFileNum, Line
Next
Close OutputFileNum
End Sub
不要忘记您需要在包含逗号的任何字段周围加上引号。
答案 1 :(得分:9)
Tony的答案通常有效,但不处理您的文字包含逗号或引号的情况。您可能更喜欢使用Workbook.SaveAs方法。
如果要将Sheet1的内容另存为单独的csv文件,请执行以下示例。
Sub create_csv()
Dim FileName As String
Dim PathName As String
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")
FileName = "filename.csv"
PathName = Application.ActiveWorkbook.Path
ws.Copy
ActiveWorkbook.SaveAs FileName:=PathName & "\" & FileName, _
FileFormat:=xlCSV, CreateBackup:=False
End Sub
想象一下,您的Sheet1包含:
lorem ipsum
lore,m ips"嗯"
输出csv文件将是:
LOREM,存有
"传说,米"" IPS""嗯"""
答案 2 :(得分:1)
您可以编写一个宏,以便从VBA以CSV格式保存当前工作簿(打开的Excel文件):
ActiveWorkbook.SaveAs Filename:="C:\Book1.csv", _
FileFormat:=xlCSVMSDOS, CreateBackup:=False
答案 3 :(得分:0)
对于那些手动编写 CSV 的人,您需要处理逗号、双引号和换行符。
例如
Sub WriteToCsv(Items() as String)
OutFile = FreeFile
Open "Outfile.csv" For Output As #OutFile
Print #OutFile, "Header"
For Each Item In Items
If InStr(1, Item, Chr(34)) > 0 Then Item = Chr(34) & Replace(Item, Chr(34), Chr(34) & Chr(34)) & Chr(34)
If InStr(1, Item, ",") > 0 And Left(Item, 1) <> Chr(34) Then Item = Chr(34) & Item & Chr(34)
If InStr(1, Item, vbLf) > 0 And Left(Item, 1) <> Chr(34) Then Item = Chr(34) & Item & Chr(34)
Print #OutFile, Item
Next
Close OutFile
End Sub