简体   繁体   English

应用条件格式时错误 9 下标超出范围

[英]Error 9 subscript out of range when applying conditional formatting

I want to apply some conditional formatting to my sheet, it errors out my code below我想对我的工作表应用一些条件格式,它在下面的代码中出错

the line that errors out is出错的行是

MyRange.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

do you think that i have the 2nd row hidden, may impact the method?你认为我隐藏了第二行,可能会影响方法吗?

Sub DraxCXLImport()

   Dim header As Integer
   Dim r As Integer
   
   On Error GoTo ErrorHandler
   
   Application.EnableEvents = False
   
   Worksheets("APM").Activate
   
   Range("A1").CurrentRegion.Select
   r = Selection.Rows.Count
   
   If r < 3 Then
       r = 3
   End If
   Worksheets("Cxl Policies").Activate
   
   'drag down formulas
   Worksheets("Cxl Policies").Range("A2:AA" & r).FillDown
   
   
   
  
   
   
   'add conditional formatting
   
   'Define Range
   Dim MyRange As Range
   
   
   Set MyRange = Worksheets("Cxl Policies").Range("S2:T" & r)

  'Delete Existing Conditional Formatting from Range
   MyRange.FormatConditions.Delete


       'Apply Conditional Formatting to Tier cancellation hours

   MyRange.FormatConditions.Add Type:=xlExpression, Formula1:="=$S3<>$T3"
   MyRange.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
   
   With Selection.FormatConditions(1).Interior
      .PatternColorIndex = xlAutomatic
       .Color = 65535
       .TintAndShade = 0
   End With
   
   Selection.FormatConditions(1).StopIfTrue = False
   
  
   
   
   
   
    'remove duplicates
   Worksheets("Cxl Policies").Range("A1:AA" & r).RemoveDuplicates Columns:=Array(1, 2), header:=xlYes
   
   
   
   Worksheets("Cxl Policies").Rows(2).Hidden = True
   
   Worksheets("Cxl Policies").Range("A1").Select
   
   
   Application.EnableEvents = True

Exit Sub

ErrorHandler:
   MsgBox Err.Number & " " & Err.Description
   
   Err.Clear
   Application.EnableEvents = True
   Resume Next
End Sub

You're using both MyRange and Selection in the line that's erroring - that's probably the cause of the problem.您在出错的行中同时使用了MyRangeSelection - 这可能是问题的原因。

However, FormatConditions.Add() returns the added FormatCondition , so you can simplify your code by using the return value directly in a With block:但是, FormatConditions.Add()返回添加的 FormatCondition ,因此您可以通过直接在With块中使用返回值来简化代码:

Dim MyRange
'...
'...
Set MyRange = Worksheets("Cxl Policies").Range("S2:T" & r)

MyRange.FormatConditions.Delete

With MyRange.FormatConditions.Add(Type:=xlExpression, Formula1:="=$S3<>$T3")

   .SetFirstPriority
   
   With .Interior
       .PatternColorIndex = xlAutomatic
       .Color = 65535
       .TintAndShade = 0
   End With
   
   .StopIfTrue = False

End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM