简体   繁体   中英

How do I loop through the cells in a Row to add to a string?

I'm trying to write a Macro in Excel to format and copy the current selection. As a part of this, I want to loop through all of the cells to do formatting conditionally on their row (the first row is a little different). What would make the most sense to me is "Rows()", but it returns a mismatch error in the For Each loop. Any ideas how I could fix this? (Also, it should work with the number of rows as a variable based on the selection, for now I'm just trying it with 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

Thanks!

Use a Range varible type and iterate through all of the IterateRange.Rows property, where IterateRange is whatever range you want to go through each row in.

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

Say Selection is an arbitrary rectangular range somewhere in the worksheet. We want to create another range that is only the third row of that range:

Sub TheThirdRow()
    Dim r As Range, rThirdRow As Range
    Set r = Selection
    Set rThirdRow = Intersect(r(3, 1).EntireRow, r)
    rThirdRow.Select
End Sub

you can loop over the cells in rThirdRow, etc.

Similar for the second or fourth row, etc.

rSelection.Rows(2)更改为rSelection.Rows(2).Cells以修复您rSelection.Rows(2).Cells的错误

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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