更改范围的条件格式

时间:2017-04-11 04:14:34

标签: excel vba excel-vba

我需要有条件地格式化三个向左/向右移动的列,具体取决于加载的数据。条件是单元格值是否为空(="")。我真的很难想出这个。

这是我的设置:

Sub Conditional_Format()
    Dim ws2 As Worksheet
    Dim lRow3 As Long, lCol3 As Long
    Dim rng8 As Range, rng9 As Range

    Set ws2 = Worksheets("Unfav GT500 Comments")

    With ws2
        lRow3 = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol3 = .Cells(3, .Columns.Count).End(xlToLeft).Column

        Set rng8 = .Range(.Cells(4, lCol3 - 2), .Cells(lRow3 - 1, lCol3 - 1))
        Set rng9 = .Range(.Cells(4, lCol3), .Cells(lRow3 - 1, lCol3))
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

对于动态更改范围,我建议使用搜索来首先定位列。您是否有任何固定的唯一列标题以及电子表格的任何特定区域?如果是这样,请使用以下内容进行搜索。您可以更改格式和列标题以适合您的数据。

'Below row will get you the column header. Repeat this line to search for the three columns.
ws2.Cells.Find(What:="Specific_Column_Header", LookIn:= xlValues).Activate
startrow = ActiveCell.Row

For row1 = startrow to ws2.Cells(.Rows.Count, "A").End(xlUp).Row
    If Cells(row1, ActiveCell.Column) = "" Then
        'Set your format here
        Cells(row1,ActiveCell.Column).Select
        With Selection.Interior
            .Pattern = xlSolid
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = -0.15
        End With
    End If
Next