2

我有一个简单的宏,可以将所需的单元格导出到 txt 文件。我可以选择一系列单元格,而不是单独告诉宏我要导出哪些单元格吗?

这是我拥有的非常简单的代码:

Sub TEST()
    Open "C:\text.txt" For Output As #1
        Print #1, Cells(1, 1) & Cells(1, 2)
        Close
End Sub

有了它,我可以导出 Excel 工作表单元格 A1、A2。但是如果我想导出大范围的单元格,这种方法就不太方便了。那么有没有办法,比如说轻松导出单元格 A1:A100?

谢谢!

4

4 回答 4

3

我看到 joseph4tw 已经回复了,但我的答案有点不同,可能会给你另一个想法,所以我还是把它放在这里。

Sub TEST()
    Dim c As Range, r As Range
    Dim output As String
    For Each r In Range("A1:C3").Rows
        For Each c In r.Cells
            output = output & c.Value & ","
        Next c
        output = output & vbNewLine
    Next r
    Open "H:\My Documents\text.txt" For Output As #1
    Print #1, output
    Close
End Sub
于 2013-02-28T01:18:11.493 回答
1

您可以使用InputBox并将类型设置为8,这将允许用户在 Excel 中单击并选择一个范围。

这是一个例子:

Sub test()
    Dim r As Excel.Range, cell As Excel.Range
    On Error Resume Next
    Set r = Application.InputBox("Select Range", "Select Range", Type:=8)
    On Error GoTo 0
    If r Is Nothing Then Exit Sub

    Open "C:\text.txt" For Output As #1
    For Each cell In r
        Print #1, cell.Value
    Next
    Close
End Sub
于 2013-02-28T01:12:24.200 回答
1

我注意到 mkingston 的示例将逗号放在首位。这将导致一切从 .csv 的第二列开始(第一列为空白)。更好的办法是将逗号放在语句的末尾。您可以使用 REPLACE() 删除最后一个“,”,但这不是必需的。

   Dim c As range, r As range
        Dim output As String
        For Each r In range(DataRange).Rows
            For Each c In r.Cells
                output = output & c.Value & ","
            Next c
            output = output & vbNewLine

        Next r
于 2014-08-21T16:43:41.987 回答
0

如果要选择所有非空单元格(连续),请使用:

Range("A1").CurrentRegion.Select

然后,您可以以任何您喜欢的方式导出它;)

于 2013-12-10T16:28:54.357 回答