繁体   English   中英

Excel中的宏-在Excel中循环范围并将值写入txt文件

[英]Macro in excel - Loop range in excel and write values to txt file

我有一个宏,该宏在Excel范围内循环并将值写入txt文件。

例如,在范围A1:C3中,txt文件中的结果将是:

$A$1    ab
$A$2    abc
$A$3    abcd
$B$1    abcde
$B$2    abcdef
$B$3    abcdefg
$C$1    abcdefgh
$C$2    abcdefghi
$C$3    abcdefghij

原则上,我需要将这两个宏合并为一个:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:E6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol
End Sub

Dim s As String
Dim n As Integer

n = FreeFile()
Open "/Users/Kuba/Desktop/a.txt" For Output As #n

s = "Hello, world!"
Debug.Print s ' write to immediate
Print #n, s ' write to file

Close #n

感谢您的任何建议。 JS

只需使用嵌套循环遍历行号和列号即可,如下所示:

Sub LoopAndWrite()

Dim FF As Byte
FF = FreeFile()

Open "/Users/Kuba/Desktop/a.txt" For Output As #FF

For c = 1 To 3 '// columns 1 to 3 (A:C)
    For r = 1 To 3 '// rows 1 to 3
        Print #FF, Cells(r, c).Address & " - " & Cells(r, c).Value
    Next
Next

Close #FF

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM