【问题标题】:How to remove the empty line that excel makes when creating a csv file using vba使用vba创建csv文件时如何删除excel产生的空行
【发布时间】:2016-05-12 18:58:26
【问题描述】:

你们中的一些人可能知道,excel 在 CSV 文件的末尾创建一个空行。我正在寻找可以删除/删除此行的解决方案,因为我想将 CSV 文件上传到无法处理此空行的其他程序。

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

有没有人可以解决这个问题,使用 VBA 删除 CSV 文件中的最后一行?

【问题讨论】:

    标签: vba excel csv export-to-csv excel-2013


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      尝试调用此 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
      

      【讨论】:

      • 感谢您的回答@EngJon。您的代码将 10 行转换为一行。 csv 文件包含大约 10 行加上最后一行是空的,必须删除。如果我的问题不够清楚,我很抱歉。
      • 嗯,它不应该这样做。 Chr(10) 应该添加换行符,因此原始行将保留。请尝试 vbCrLf 而不是 Chr(10) 并告诉我它是否有效。
      • 没问题,我会相应地编辑我的答案。然后随意接受它作为答案;)
      猜你喜欢
      • 2020-12-25
      • 1970-01-01
      • 2018-03-24
      • 2016-12-26
      • 1970-01-01
      • 2020-03-22
      • 2013-10-18
      • 1970-01-01
      • 2012-03-11
      相关资源
      最近更新 更多