我有一个循环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
答案 0 :(得分:0)
只需使用嵌套循环来遍历行号和列号,如下所示:
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