如何修改VBA代码避免生成TXT文件时末尾出现空行
解决VBA生成TXT文件末尾空行问题
你的代码出现末尾空行,是因为Print #1语句默认会在输出内容末尾自动追加回车换行符,加上循环中每行都添加vbCrLf,即便截取了最后2个字符,最终还是会多出一行空行。
以下是两种可靠的修改方案:
方案一:使用数组拼接内容(推荐,效率更高)
通过数组存储每行数据,再用Join函数统一添加换行符,最后用带分号的Print语句避免自动追加换行:
Sub GenerateTxtFile() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim filePath As String Dim txtLines() As String Dim lineCount As Long Set ws = ActiveSheet ' 如需指定工作表,替换为Sheets("你的表名") filePath = ThisWorkbook.Path & "\RxH.txt" With ws lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row lineCount = lastRow - 1 ' 计算需要导出的数据行数(跳过表头) ' 无数据时直接提示退出 If lineCount < 1 Then MsgBox "没有可导出的数据!", vbExclamation Exit Sub End If ReDim txtLines(1 To lineCount) For i = 2 To lastRow Dim invoiceNo As String invoiceNo = .Cells(i, "C").Value Dim dashIndex As Long dashIndex = InStr(1, invoiceNo, "-") ' 拼接单条数据,不添加换行 txtLines(i - 1) = _ Replace(.Cells(i, "A").Value, ",", "") & "|" & _ "R1" & "|" & _ Left(invoiceNo, dashIndex - 1) & "|" & _ Mid(invoiceNo, dashIndex + 1) & "|" & _ Format(.Cells(i, "B").Value, "dd/mm/yyyy") & "|" & _ Replace(.Cells(i, "D").Value, ",", "") Next i End With ' 用Join函数给行与行之间添加换行符,末尾无多余换行 Dim txtData As String txtData = Join(txtLines, vbCrLf) ' 写入文件,分号阻止Print自动追加换行 Open filePath For Output As #1 Print #1, txtData; Close #1 MsgBox "TXT文件生成成功!", vbInformation End Sub
方案二:直接修改写入逻辑
如果你不想改动拼接部分,只需修改文件写入的代码,替换原有的Print语句为Put,避免自动追加换行:
' 替换原代码中写入文件的部分 Open filePath For Output As #1 Put #1, , Mid(txtData, 1, Len(txtData) - 2) Close #1
修改说明
- 方案一优势:数组拼接比循环累加字符串更高效,大数量数据下性能提升明显,从根源上避免末尾多余换行。
- 方案二优势:改动最小,仅调整写入语句,适合快速修复现有代码。
内容的提问来源于stack exchange,提问作者Carl
相关产品推荐
相关产品推荐

