跳过空白行时将数据写入文本文件

时间:2018-09-05 17:37:56

标签: excel vba

我正在使用下面的宏将选定范围(在Excel中)写入.txt文件。

Sub ExportTXT()

Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer

myFile = Application.DefaultFilePath & "\sales.txt"
Set rng = Range(Cells(1, 1), Cells(10, 4))

Open myFile For Output As #1

    For i = 1 To rng.Rows.Count
        For j = 1 To rng.Columns.Count
            cellValue = rng.Cells(i, j).Value

            If j = rng.Columns.Count Then
                Write #1, cellValue
            Else
                Write #1, cellValue,
            End If
        Next j
    Next i

Close #1

End Sub

我正在尝试跳过第3行和第9行。
enter image description here

当前输出-用红色圈出的行是不应写入txt文件的行。
enter image description here

如何跳过空白行?

我尝试使用 Isempty(cellValue)= True **和空字符串**“” 条件语句。

我的txt文件输出应如下所示 enter image description here

关于如何检查cellValue内容以查看其是否为空并仅写有数据行的任何想法。

1 个答案:

答案 0 :(得分:2)

我对您的代码做了一些更改

Sub ExportTXT()

Const DELIMITER = ","

Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer
Dim sngRow As Range
Dim vDat As Variant    

    myFile = Application.DefaultFilePath & "\sales.txt"
    With ActiveSheet
        Set rng = .Range(.Cells(1, 1), .Cells(10, 4))
    End With

    Dim noCol As Long
    noCol = rng.Columns.Count    

    Open myFile For Output As #1

    For Each sngRow In rng.Rows

        vDat = WorksheetFunction.Transpose(WorksheetFunction.Transpose(sngRow))
        vDat = Join(vDat, DELIMITER)
        If Len(vDat) >= noCol Then
            Write #1, vDat
        End If

    Next

    Close #1

End Sub

更新基于其中一项评论,请使用以下声明以避免“文字限定”

Print #1, vDat

代替

Write #1, vDat