Excel VBA - 遍历单元格列,然后遍历行的单元格

时间:2017-03-17 10:29:05

标签: vba excel-vba for-loop excel

如果在Column中找到了值,我希望它开始迭代首先找到该值的那行的Cells。我已经使用嵌套的FOR Loops来尝试它,但仍然无法解决它。有解决方案的人吗?

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

1 个答案:

答案 0 :(得分:0)

正如您在评论中看到的,您的问题是Cells的语法。请尝试以下方法:

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