突出显示在选定范围内至少重复特定次数的值

时间:2018-02-12 23:47:30

标签: excel vba excel-vba conditional-formatting

我目前正在尝试解决我的宏(VBA)问题。实际上,我希望创建一个要求特定数字的子,然后在我想要选择的变量范围内突出显示至少重复这些次数的值。

经过一番研究,我得出了这个:

Sub HighlightOccurences()

Dim Val As String
Val = InputBox("Please enter a random number")
MsgBox "Ok, now I will show the values that are duplicated at least this number of times within the selected range"

Dim Rng As Range
Dim cel As Variant
Dim OccurenceCounter As Integer

Set Rng = Range.Select

OccurenceCounter = 0

For Each cel In Rng
    If WorksheetFunction.CountIf(Rng, cel.Value) > 0 Then
        OccurenceCounter = OccurenceCounter + 1
    End If
Next cel

For Each cel In Rng
    If OccurenceCounter = Val Then
        cel.Interior.Color = RGB(255, 255, 204)
    End If
Next cel

End Sub

然而,这显然不起作用,即使我知道问题在哪里(选择过程"以及突出显示部分),我也无法用我在网上找到的东西来解决它们。

我希望有人可以帮我一点,

非常感谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

Option Explicit

Sub HighlightOccurences()

    Dim randNumber As Long
    randNumber = Application.InputBox("Please enter a random number", Type:=1)

    Dim rng As Range, cel As Range
    Set rng = Application.InputBox("Choose Range to Highlight", Type:=8)

    For Each cel In rng
        If WorksheetFunction.CountIf(rng, cel.Value) >= randNumber Then
            cel.Interior.Color = RGB(255, 255, 204)
        End If
    Next cel

End Sub

答案 1 :(得分:1)

创建条件格式规则。

Option Explicit

Sub HighlightOccurences()
    Dim val As Long, addr As String
    val = Application.InputBox("Please enter a random number", Type:=1)
    MsgBox "Ok, now I will show the values that are duplicated at least this number of times within the selected range"

    With Selection
        addr = .Cells(1).Address(0, 0)
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:="=countif(" & .Address & ", " & addr & ")>=" & val
        .FormatConditions(1).Interior.Color = 120000
    End With
End Sub

这并没有摆脱CFR,但这是不言而喻的,你的原始代码和叙述也没有消除亮点。