导出Excel范围到TXT停止在空单元格

时间:2017-10-27 16:03:21

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

找到以下脚本

Sub saveText2()
Dim filename As String, lineText As String
Dim myrng As Range, i, j

filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

Open filename For Output As #1

Set myrng = Range("Name")

For i = 1 To myrng.Rows.Count
    For j = 1 To myrng.Columns.Count
        lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
    Next j
    Print #1, lineText
Next i
Close #1
End Sub

但我似乎没有设法在第一个空行停止循环。

我曾尝试添加DO而myrng<> “”循环,但我不知道在哪里应用代码。

1 个答案:

答案 0 :(得分:0)

不确定这是我最聪明的方式,但我最终还是设法做到了这一点:

Sub saveText2()
Dim filename As String, lineText As String
Dim myrng As Range, i, j

filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

Open filename For Output As #1

Set myrng = Range("A:B")

For i = 1 To myrng.Rows.Count
    For j = 1 To myrng.Columns.Count

    If IsEmpty(myrng.Cells(i, j)) = True Then
    Close #1
    Exit Sub
    End If

        lineText = IIf(j = 1, "", lineText & " ") & myrng.Cells(i, j)
    Next j
    Print #1, lineText
Next i
Close #1
End Sub