将Excel范围导出到.txt文件时获取额外的空行

时间:2017-12-08 19:56:53

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

我正在尝试将Excel范围复制到.txt文件。

导出成功,但有一个例外,它增加了一个" 额外"最后的空行。

我已经阅读并测试了 SO (以及其他网站)上的许多解决方案,但仍未取得任何成功。

我的代码(相关部分)

' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        Print #1, lineText
        lineText = ""
    Next i
End With
Close #1

我的StockSht(工作表对象)和LastRow已正确定义,并获取其值。

导出的.txt文件结尾的屏幕截图

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试使用;在最后一条印刷线上。 ' ===导出到.txt文件=== Dim TxtFileName As String,lineText As String TxtFileName = ThisWorkbook.Path& " \ INV _" &安培;格式(日期," yyyymmdd")& " .TXT" 打开TxtF​​ileName输出为#1 使用StockSht     对于i = 1到LastRow         对于j = 1到3             如果j = 3那么                 lineText = lineText& .Cells(i,j).Value2             其他' j = 1或2                 lineText = lineText& .Cells(i,j).Value2& vbTab             万一         下一个j         如果i = LastRow那么             打印#1,lineText;         其他             打印#1,lineText         万一         lineText =""     下一个我 结束 关闭#1

答案 1 :(得分:2)

您可以在Print语句中使用分号来控制插入点(即阻止最后一行的换行)。

MSDN页面上的相关位:

  

在显示最后一个字符后立即使用分号定位插入点。

我测试了这段代码:

Sub PrintTest()

    Dim lng As Long

    Open "C:\foo3.txt" For Output As #1

    For lng = 1 To 10
        If lng < 10 Then
            Print #1, "foo" & lng
        Else
            Print #1, "foo" & lng; '<-- semi-colon prevents the newline
        End If
    Next lng

    Close #1

End Sub

所以我会更新你的代码,如下所示(未经测试):

' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j

        '--- new bit: check for i against LastRow and add the semicolon on last row
        If i <> LastRow Then
            Print #1, lineText
        Else
            Print #1, lineText; '<-- semi colon keeps insertion point at end of line
        End If


        lineText = ""
    Next i
End With
Close #1
相关问题