如何删除使用 vba 创建 csv 文件时 excel 生成的空行

How to remove the empty line that excel makes when creating a csv file using vba

有些人可能知道,excel 会在 CSV 文件的末尾创建一个空行。我正在寻找可以 remove/delete 这一行的解决方案,因为我想将 CSV 文件上传到另一个无法处理这一空行的程序。

起初我以为这是我创建 CSV 文件的方式,但在花了几个小时搜索解决方案后,我发现这是一个错误。

是否有人有解决此问题的方法,使用 VBA 删除 CSV 文件中的最后一行?

尝试调用此 Sub 来终止 csv 文件的最后一行。您必须将路径插入代码中:

Sub KillLastLine()
    Dim fso As New FileSystemObject
    Dim ts As TextStream
    Dim filecontent As String
    Dim myFile As File

    Set myFile = fso.GetFile("YourCSVPathHere")
    Set ts = myFile.OpenAsTextStream(ForReading)
    While Not ts.AtEndOfStream
        filecontent = filecontent & ts.ReadLine & vbCrLf
    Wend
    Set ts = myFile.OpenAsTextStream(ForWriting)
    ts.Write Left(filecontent, Len(filecontent) - 1)
    ts.Close
End Sub
Sub ZUtil_TextFile_FindReplace(FilePath As String, strOld As String, strNew As String)
'PURPOSE: Modify Contents of a text file using Find/Replace
'SOURCE: www.TheSpreadsheetGuru.com
Dim TextFile As Integer
Dim FileContent As String
'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile
'Open the text file in a Read State
  Open FilePath For Input As TextFile
'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
  Close TextFile
'Find/Replace
  FileContent = Replace(FileContent, strOld, strNew)
  FileContent = Replace(FileContent, "^(?:[\t ]*(?:\r?\n|\r))+", "")
  If Right(FileContent, 2) = Chr(13) & Chr(10) Then
    FileContent = Left(FileContent, Len(FileContent) - 2)
  End If
'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile
'Open the text file in a Write State
  Open FilePath For Output As TextFile
'Write New Text data to file
  Print #TextFile, FileContent
'Close Text File
  Close TextFile
  'MsgBox "ZUtil_TextFile_FindReplace TERMINADO"
End Sub