如何在VBA中的整个列中应用条件格式

时间:2017-01-18 19:41:19

标签: excel vba excel-vba

所以,我正在尝试编写一个宏,它允许我在电子表格中找到一个值,将其存储为名为“TotalHooks”的变量,然后在不同的列中将值着色为“Count5s”,如果它们等于(TotalHooks - 1)。我已经成功找到并将此条件应用于“Count5s”列中的第一个单元格,但不知道如何使该公式条件正确应用于列中的其余数字。这是我的代码:

Dim TotalHooks As Integer
Dim StraightLiner As Integer

Cells.Find(What:="TotalHookCount", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Offset(1, 0).Activate

TotalHooks = ActiveCell.Value

StraightLiner = TotalHooks - 1

Cells.Find(What:="Count5s", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Offset(1, 0).Activate
    If ActiveCell = StraightLiner Then
        With Selection.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .ThemeColor = xlThemeColorAccent4
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
        With Selection.Font
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = 0
        End With
    End If

1 个答案:

答案 0 :(得分:0)

你需要编写一个循环,它执行Find,然后查找FindNext以保持搜索。我没有测试过这段代码,但我会按照以下几点写一些东西:

Dim TotalHooks As Integer
Dim StraightLiner As Integer
Dim row As Long
Dim curCell As Range


Cells.Find(What:="TotalHookCount", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Offset(1, 0).Activate

TotalHooks = ActiveCell.Value

StraightLiner = TotalHooks - 1

Dim cellFound As Range
Set cellFound = Cells.Find(What:="Count5s", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
row = 1
If Not cellFound Is Nothing Then
    Do While Not IsEmpty(cellFound.Offset(row, 0))
        Set curCell = cellFound.Offset(row, 0)
        If curCell = StraightLiner Then
        With curCell.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .ThemeColor = xlThemeColorAccent4
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
        With curCell.Font
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = 0
        End With
        End If
        row = row + 1
    Loop
End If