导出/转换为CSV时,将第一行替换为换行符

时间:2018-02-02 00:52:21

标签: excel vba csv

编辑:我改变了这个原始帖子,因此我可以嵌入我想要的最终代码。 使用底部的代码导出特定工作表并转换为CSV文件。 输出文件将始终具有以空格开头,后跟字符串

的第一行
,,Primary,Secondary,Tertiary

我想用换行符删除/替换该行。即.. 电流:

 ,,Primary,Secondary,Tertiary
100,106,2165483624,2165483624,8133181331

我想用换行删除/替换该顶行。即:

(newline here)
100,106,2165483624,2165483624,8133181331

该行始终是第一行,并且将是唯一以空格和两个逗号开头的行,也是唯一一个带有Primary,Secondary,Tertiary逗号分隔的行。 我花了几个小时检查这个网站和其他人,但要么 我使用了错误的关键字,或者我没有想要的结果 记录在案。提前谢谢。

我最终使用的代码

Sub btn_Export_to_CSV_Click()

Dim csvFilePath As String
Dim fileNo As Integer
Dim fileName As String
Dim oneLine As String
Dim lastRow, lastCol As Long
Dim idxRow, idxCol As Long
' --- get this file name (without extension)
fileName = Left(ActiveWorkbook.Name, InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) - 1)
' --- create file name of CSV file (with full path)
csvFilePath = ActiveWorkbook.Path & "\" & fileName & ".csv"
' --- get last row and last column
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' --- open CSC file
fileNo = FreeFile
Open csvFilePath For Output As #fileNo
Print #fileNo, ""   ' -- write one blank line
' --- row loop
For idxRow = 2 To lastRow
    oneLine = ""
    ' --- column loop: concatenate oneLine
    For idxCol = 1 To lastCol
        If (idxCol = 1) Then
            oneLine = Cells(idxRow, idxCol).Value
        Else
            oneLine = oneLine & "," & Cells(idxRow, idxCol).Value
        End If
    Next
    ' --- write oneLine > CSV file
    Print #fileNo, oneLine  ' -- Print: no quotation (output oneLine as it is)
Next
' --- close file
Close #fileNo
MsgBox "CSV file completed !!" & Chr(13) & csvFilePath

End Sub

0 个答案:

没有答案