[英]Append Rows to CSV File (VBA)
我在 MrExcel 上從 TommyGun 借用了以下代碼,但遇到了以下困難:
在生成文件的末尾,它會重復下面行中的分隔符,即使它們之間沒有數據;
文件名必須根據我們所處的月份動態生成,但 'Const CSVFile As String' 不接受 Format(date, "mmm-yy") 作為字符串元素,例如。
Sub Append2CSV()
Dim tmpCSV As String 'string to hold the CSV info
Dim f As Integer
Const CSVFile As String = "C:\VBA Code\test.csv" 'replace with your filename
f = FreeFile
Open CSVFile For Append As #f
tmpCSV = Range2CSV(Range("A2:H3"))
Print #f, tmpCSV
Close #f
End Sub
Function Range2CSV(list) As String
Dim tmp As String
Dim cr As Long
Dim r As Range
If TypeName(list) = "Range" Then
cr = 1
For Each r In list.Cells
If r.Row = cr Then
If tmp = vbNullString Then
tmp = r.Value
Else
tmp = tmp & "," & r.Value
End If
Else
cr = cr + 1
If tmp = vbNullString Then
tmp = r.Value
Else
tmp = tmp & Chr(10) & r.Value
End If
End If
Next
End If
Range2CSV = tmp
End Function
如何考慮以下內容:如果文件不存在,則使用 header(第 1 行)創建它。 如果是,那么 append (range"A2:S" & lastorw)
我無法復制第一個問題(output CSV 中分隔符的尾隨行)。 為了使您的文件名動態化,它應該作為Dim
(而不是常量表達式Const
)給出,或者您應該對常量表達式使用字符串Replace
。 使用如下Dim
變量:
Option Explicit
Sub Append2CSV()
Dim tmpCSV As String 'string to hold the CSV info
Dim f As Integer
Dim CSVFile As String
CSVFile = "C:\VBA Code\" & Format(Date, "MMM-YY") & ".csv"
f = FreeFile
Open CSVFile For Append As #f
tmpCSV = Range2CSV(Range("A2:H3"))
Print #f, tmpCSV
Close #f
End Sub
輸入數據:
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.