我正在尝试将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文件末尾的屏幕截图

vba - 将Excel Range导出到.txt文件时获得额外的空行-LMLPHP

最佳答案

尝试在最后一个打印行上使用;

' === 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
        If i = LastRow Then
            Print #1, lineText;
        Else
            Print #1, lineText
        End if
        lineText = ""
    Next i
End With
Close #1

关于vba - 将Excel Range导出到.txt文件时获得额外的空行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47721311/

10-10 09:58