【问题标题】:Write data to text file while skipping blank rows在跳过空白行的同时将数据写入文本文件
【发布时间】:2018-09-05 17:37:55
【问题描述】:

我正在使用下面的宏将选定范围(在 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 行。

当前输出 - 红色圈出的行是不应写入 txt 文件的行。

如何跳过空白行?

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

我的 txt 文件输出应该是这样的

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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我稍微修改了你的代码

    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
    

    更新基于其中一个 cmets 使用以下语句以避免“文本限定”

    Print #1, vDat
    

    而不是

    Write #1, vDat
    

    【讨论】:

    • 您可能已将其更改为“损坏”。 Write 语句不只是用逗号分隔输出 - 它还用文本限定字符串(虽然效果不佳)。
    • @Comintern:不知道你的意思,但这可能是因为我的英语水平。
    • NP - 如果你有一个字符串 - x = "foo" 并使用 Write #1, x,它将在文本文件中用双引号括起来。你会得到"foo" 而不是简单的foo。事先使用Join 会将整行 括在双引号中。运行您的代码并查看输出 - 您会明白我的意思。
    • 啊,我明白了,但这可以通过使用 Print 轻松解决,对吧?
    • 如果字符串不需要双引号,可以。它主要取决于 OP 的输出规范。 Write 旨在与 Input 一起阅读 - Print 不进行格式化。无论哪种情况,最好在字符串中转义 ," 等内容,但 OP 的数据看起来相当简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2021-06-28
    • 2021-11-13
    相关资源
    最近更新 更多