我正在尝试在Excel中编写宏来格式化和复制当前选择。作为其中的一部分,我想循环遍历所有单元格以在其行上有条件地进行格式化(第一行有点不同)。对我来说最有意义的是“Rows()”,但它会在For Each循环中返回不匹配错误。我有什么想法可以解决这个问题? (另外,它应该根据选择将行数作为变量使用,现在我只是用1-4来尝试。)
Sub Convert()
Dim sOutput As String
Dim rSelection As Range
Dim rCell As Range
Dim rHead As Range
Set rSelection = Selection.Cells
Set rHead = rSelection.Rows(1)
sOutput = "||"
For Each rCell In rHead
sOutput = sOutput & rCell.Value & "||"
Next rCell
sOutput = sOutput & Chr(10) & "|"
For Each rCell In rSelection.Rows(2)
sOutput = sOutput & rCell.Value & "|"
Next rCell
'sOutput = sOutput & Chr(10) & "|"
For Each rCell In rSelection.Rows(3)
sOutput = sOutput & rCell.Value & "|"
Next rCell
'sOutput = sOutput & Chr(10) & "|"
For Each rCell In rSelection.Rows(4)
sOutput = sOutput & rCell.Value & "|"
Next rCell
fCopy (sOutput)
MsgBox "Table has been copied and formatted."
End Sub
谢谢!
答案 0 :(得分:0)
使用Range
变量类型并遍历所有Iterate Range.Rows属性,其中IterateRange
是您想要遍历每行的任何范围。
Private Sub rowTester()
Dim mRow As Range
For Each mRow In Range("A1:B4").Rows
Debug.Print mRow.Row
'your code here which will execute on each row in the above range
Next mRow
End Sub
答案 1 :(得分:0)
Say Selection是工作表中某处的任意矩形范围。我们想要创建另一个范围,它只是该范围的第三行:
Sub TheThirdRow()
Dim r As Range, rThirdRow As Range
Set r = Selection
Set rThirdRow = Intersect(r(3, 1).EntireRow, r)
rThirdRow.Select
End Sub
你可以循环遍历rThirdRow中的单元格
类似于第二或第四行等等。
答案 2 :(得分:0)
将rSelection.Rows(2)
更改为rSelection.Rows(2).Cells
以修复您的错误