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

Highlight values that are duplicated at least a specific number of times within a selected range

我目前正在尝试解决有关我的宏 (VBA) 的问题。事实上,我希望创建一个子程序,它要求一个特定的数字,然后突出显示在我想要 select.

的可变范围内至少重复此次数的值

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

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

然而,这显然是行不通的,即使我知道问题出在哪里("selection process" 和突出显示的部分),我无法用我在网上找到的解决它们。

希望有人能帮帮我,

非常感谢!

试试这个:

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

创建条件格式规则。

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,但这是不言而喻的,您的原始代码和叙述也没有做任何删除亮点的事情。