简体   繁体   中英

Excel VBA - Iterate through a Column of Cells and then Cells of a Row

If the value was found in the Column, I want it to start iterating through the Cells of that Row from which the value was first found. I've used nested FOR Loops to attempt it, but still couldn't figure it out. Anyone with an solution?

LastRow = Range("p" & Rows.Count).End(xlUp).Row
LastCol = Cells(LastRow & Columns.Count).End(xlToRight).Column
    For s = 1 To LastRow
        If Range("a" & s).Value = "TO BE PAID Total" Then
            For i = 1 To LastCol

                    If Cells(s & i).Value <> "" Then
                        Cells(s & i).Select
                        Selection.Style = "Accent2"
                    End If


            Next i
        End If
    Next s

As you can see in the comments, your problem is the syntax of Cells . Try the following:

Dim LastRow As Long
Dim LastCol As Long
Dim s As Integer
Dim i As Integer

LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Worksheets("Sheet1").Cells(1, Columns.Count).End(xlToLeft).Column
    For s = 1 To LastRow
        If Worksheets("Sheet1").Cells(s, 1).Value = "TO BE PAID Total" Then
            For i = 1 To LastCol
                    If Worksheets("Sheet1").Cells(s, i) <> "" Then
                        Worksheets("Sheet1").Cells(s, i).Style = "Accent2"
                    End If
            Next i
        End If
    Next s

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