将条件格式应用于变量范围

时间:2016-09-15 17:32:40

标签: excel vba

我希望这个宏选择范围C6:N6,应用格式条件,步骤7等等,直到我的列表结束。 当我执行它时,它会给我一个关于对象的错误。

我认为我的问题出现在以下部分:

For i = 6 To lastRow Step 7
    Range(C & i, N & i).Select 

这样我想让范围变量。 以下是我的代码:

Sub test1()
' Coluna C

Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Pega ultima celula com valores na coluna C

For i = 6 To lastRow Step 7
    Range(C & i, N & i).Select 'what am i missing?

         With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _
        Formula1:="=0"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False


Next i


End Sub

1 个答案:

答案 0 :(得分:0)

不是将其保留在评论中,而是回答您的问题 您的代码将CN视为变量,而应将其视为文字。为此,您需要将它们用双引号(")括起来。而不是

Range(C & i, N & i).Select

你需要做

Range("C" & i, "N" & i).Select

您的lastRow作业也存在一个问题。根据您的评论,您希望获取包含C列的最后一个单元格,即列3,但是您在此处传递了错误的colum索引:

lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Pega ultima celula com valores na coluna C

相反,你应该使用

lastRow = Cells(Rows.Count, 3).End(xlUp).Row ' <-- column C is index 3

我添加此内容是因为如果您的列A未正确填充,或者与所需列C

此外,正如BruceWayne(关于主题:很好的用户名,顺便说一句)所强烈建议的那样,您应该avoid .Select完全在您的代码中。您可以使用With块,与您正在执行的操作类似,并使用对单元格和范围的正确引用,而不是依赖于活动工作表。有了这个,你最终会得到一个更像下面的代码

Sub test1()
' Coluna C

    Dim lastRow As Long
    With ThisWorkbook.Worksheets("YourSheetName")
        lastRow = .Cells(.Rows.Count, 3).End(xlUp).row ' Pega ultima celula com valores na coluna C

        For i = 6 To lastRow Step 7
            With .Range("C" & i, "N" & i)

                With .Interior
                    .Pattern = xlNone
                    .TintAndShade = 0
                    .PatternTintAndShade = 0
                End With
                .FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _
                    Formula1:="=0"
                .FormatConditions(.FormatConditions.Count).SetFirstPriority
                With .FormatConditions(1).Interior
                    .PatternColorIndex = xlAutomatic
                    .Color = 255
                    .TintAndShade = 0
                End With
                .FormatConditions(1).StopIfTrue = False
            End With

        Next i
    End With

End Sub
相关问题