Sub highlight_outliers()
' 选中范围,运行后红色高亮离群值,利用条件格式实现
Q1 = WorksheetFunction.Quartile(Selection, 1)
Q3 = WorksheetFunction.Quartile(Selection, 3)
IQR = Q3 - Q1
LowerBound = Q1 - 1.5 * IQR
UpperBound = Q3 + 1.5 * IQR
' 先清除先前的条件格式
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=" & UpperBound
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=" & LowerBound
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
当工作表中没有选择任何数据的时候(有数据工作正常),运行就会报错:

--
FROM 124.162.118.*