VBA用于执行操作,直到单元符合条件

时间:2018-05-01 16:08:35

标签: excel vba excel-vba

我没有运气搜索这个,我希望你们都能帮忙。

我正在尝试在Excel中执行以下操作:

如果单元格与table1中的值匹配,请突出显示该单元格。然后突出显示它下面的单元格并继续突出显示它下面的单元格,直到它到达与table2中的值匹配的单元格。

我无法弄清楚如何在这个

的循环函数中工作

提前致谢

1 个答案:

答案 0 :(得分:0)

我写了一个简单的for循环,它循环遍历数据范围。我的数据表由整数1 - 15组成,名为“数据”。起点名为“Point_1”,终点名为“Point_2”。

代码如下,注明是为了清晰起见。本质上,它只是在单元格与Point_1匹配时切换高亮显示ON,并在单元格与Point_2匹配时突出显示直到切换为OFF。

Sub HighlightRange()
Dim cel As Range
Dim dataRange As Range
Dim highlighting As Boolean

highlighting = False

With Application.ActiveWorkbook.Sheets("Sheet1")

    Set dataRange = .Range("Data") 'This is your data range. I named mine 'Data'

    For Each cel In dataRange
        'Check for beginning or end values
        If cel = .Range("Point_1").Value Then 'This is your starting value. I named mine 'Point_1'
            highlighting = True
        ElseIf cel = .Range("Point_2").Value Then 'This is your ending value. I named mine 'Point_2'
            highlighting = False
        End If

        'While highlighting is activated, highlight the current cell
        If highlighting = True Then
            cel.Interior.ColorIndex = 5
        End If

    Next cel 'Check all cells in dataRange

End With

End Sub

值得注意的是,终点未突出显示。但是,您可以在突出显示命令之后移动ElseIf语句,该语句将突出显示返回到for循环的结尾。这将在突出显示Point_2而不是之前突出显示。本案的代码如下。

Sub HighlightRange()
Dim cel As Range
Dim dataRange As Range
Dim highlighting As Boolean

highlighting = False

With Application.ActiveWorkbook.Sheets("Sheet1")
'This code also highlights Point_2.

    Set dataRange = .Range("Data") 'This is your data range. I named mine 'Data'

    For Each cel In dataRange
        'Check for beginning or end values
        If cel = .Range("Point_1").Value Then 'This is your starting value. I named mine 'Point_1'
            highlighting = True
        End If

        'While highlighting is activated, highlight the current cell
        If highlighting = True Then
            cel.Interior.ColorIndex = 5
        End If

        If cel = .Range("Point_2").Value Then 'This is your ending value. I named mine 'Point_2'
            highlighting = False
        End If

    Next cel 'Check all cells in dataRange

End With

End Sub

我希望这有帮助!您可以将高亮颜色从蓝色(colorIndex = 5)更改为您喜欢的任何颜色。如果单击“录制宏”并根据需要格式化单元格,则可以将生成的代码复制到此宏中以代替以下行:

cel.Interior.ColorIndex = 5

干杯和祝你好运!