0

我正在尝试在 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

谢谢!

4

3 回答 3

0

使用Range变量类型并遍历所有 IterateRange.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
于 2013-10-03T15:31:04.853 回答
0

假设选择是工作表中某处的任意矩形范围。我们想创建另一个范围,它只是该范围的第三行:

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 等中的单元格。

第二排或第四排类似,以此类推。

于 2013-10-03T15:37:14.483 回答
0

更改rSelection.Rows(2)rSelection.Rows(2).Cells修复您遇到的错误

于 2013-10-03T15:52:54.110 回答