在VBA中使用for循环标识行

时间:2019-06-27 16:35:12

标签: excel vba for-loop

我通常使用R进行编码,这是我第一次发布有关VB相关的任何内容,因此我对这个newb问题表示歉意。预先,我尝试寻找解决方案hereherehere,但收效甚微。

我试图根据第一列中单元格的字符串内容突出显示一行。例如,如果第一列中的单元格包含字符串“ Total”,那么我想用深色来突出显示整个行。

这是我到目前为止所拥有的:

Sub tryrow()
    Dim Years
    Dim rownum As String

    Years = Array("2007", "2008", "2009") ' short example 
    For i = 0 To UBound(Years)
        Set rownum = Range("A:A").Find(Years(i) & " Total", LookIn:=xlValues).Address
        Range(rownum, Range(rownum).End(xlToRight)).Interior.ColorIndex = 1
    Next i
End Sub

我遇到的问题是,当我尝试运行sub时收到此错误消息:

  

编译错误:需要对象

宏编辑器突出显示rownum =,就好像该对象尚未使用Dim rownum As String初始化一样。有人知道我可能做错了吗?谢谢!

2 个答案:

答案 0 :(得分:2)

您在这里遇到了几个问题,并在修复旁边显示了以下信息:

Sub tryrow()
    Dim Years() As String 'Best practice is to dim all variables with types. This makes catching errors early much easier
    Dim rownum As Range 'Find function returns a range, not a string

    Years = Array("2007", "2008", "2009") ' short example
    For i = 0 To UBound(Years)
        Set rownum = Range("A:A").Find(Years(i) & " Total", LookIn:=xlValues) 'Return the actual range, not just the address of the range (which is a string)
        If Not rownum Is Nothing Then 'Make sure an actual value was found
            rownum.EntireRow.Interior.ColorIndex = 15 'Instead of trying to build row range, just use the built-in EntireRow function. Also, ColorIndex for gray is 15 (1 is black, which makes it unreadable)
        End If
    Next i
End Sub

答案 1 :(得分:0)

您可以通过使用自动过滤器来避免循环,该方法会更快地工作。该代码假定该表从A1单元格开始:

Sub HighlightRows()

    Dim rng As Range, rngData As Range, rngVisible As Range
    '//All table
    Set rng = Range("A1").CurrentRegion
    '//Table without header
    With rng
        Set rngData = .Offset(1).Resize(.Rows.Count - 1)
    End With
    rng.AutoFilter Field:=1, Criteria1:="*Total*"
    '// Need error handling 'cause if there are no values, error will occur
    On Error Resume Next
    Set rngVisible = rngData.SpecialCells(xlCellTypeVisible)
    If Err = 0 Then
        rngVisible.EntireRow.Interior.ColorIndex = 1
    End If
    On Error GoTo 0

End Sub