首页 > 解决方案 > 循环遍历 excel 单元格强制至少有 2 个活动单元格

问题描述

我正在尝试将单元格的内容以特定格式打印到文本文件中。除非我填写了至少 2 行,否则一切正常。如果我只有 1 行,它就会崩溃。有人可以帮我吗?非常感谢!下面的代码:

Sub exportBanners()

    Dim FileName As String
    FileName = ThisWorkbook.Path & "\MT_BANNERS_" & Format(Now, "ddmmyy-hhmmss") & ".txt"

    Dim c As Range, r As Range
    Dim output As String

    Dim lRow As Long
    Dim lCol As Long

    lRow = Cells(Rows.Count, 1).End(xlUp).Row

        For Each r In Range("A9:B9", Range("A9:B9").End(xlDown)).Rows

            For Each c In r.Cells

                 output = output & "|" & c.Value

            Next c
            output = output & vbNewLine

        Next r

    Open FileName For Output As #1

    Print #1, output

    Close

    MsgBox "MT BANNERS requested successfully!"

End Sub

标签: excelvbaloopsexport-to-text

解决方案


推荐阅读