突出显示重复值,如何在msgbox Ex中显示: - 重复单元格值(2)重复3次

时间:2017-02-13 10:06:19

标签: excel vba excel-vba access-vba

我正在寻找一种在msgbox中显示动态值的方法。

Ex: - 重复单元格值(2)重复3次

这是我在代码中写的:

'this function for to highlight duplicates
Function FindingDuplicate(rng As Range, counter As Long) As Boolean
    Dim cell As Range
    'For each lopp for getting all cell values
    For Each cell In rng
     ' Checking the condition wheather cell value is reapted or not
        If WorksheetFunction.CountIf(Range(rng(1, 1), cell), cell.Value) > 1 Then
            cell.Interior.Color = vbRed
            counter = counter + 1
        Else
            cell.Interior.Pattern = xlNone
        End If
    Next
    FindingDuplicate = counter > 0
End Function   


'This is my Main()

 Sub main()
 Dim counter As Long
 'Calling Function 
 If FindingDuplicate(ActiveSheet.UsedRange, counter) Then '<--| change 'ActiveSheet.UsedRange' to whatever range you want
    MsgBox counter & " cells (red background) contain a duplicated data. Please Check"

Else
    MsgBox " Data Validation Completed. No Duplicate Found."
End If

End Sub

3 个答案:

答案 0 :(得分:1)

如果我正确理解了您的需求,您希望在消息框中包含一个动态字段,其中包含您定义的变量的值。为此,您可以尝试

MsgBox( Counter & " cells (with red background) contain duplicate data. Please check!")

其中Counter是动态字段。如果,让我们说,Counter = 3,您将获得"3 cells (with red background) contain duplicate data. Please check!"。如果这样做,您可以定制它以显示您想要显示的特定文本。

答案 1 :(得分:1)

您可能想要使用Dictionary对象(在您的VBA IDE中单击工具 - &gt;参考,向下滚动“可用参考”列表框,直到“Microsoft Scripting Runtime”条目并勾选其复选标记,最后单击“确定“按钮”

Function FindingDuplicate(rng As Range, nDupes As Long, dupes As Scripting.Dictionary) As Boolean
    Dim cell As Range
    Dim dupesCounter As Long

    For Each cell In rng
        dupesCounter = WorksheetFunction.CountIf(Range(rng(1, 1), cell), cell.Value) - 1
        If dupesCounter > 0 Then
            cell.Interior.Color = vbRed
            dupes.Item(cell.Value) = dupesCounter
        Else
            cell.Interior.Pattern = xlNone
        End If
    Next
    FindingDuplicate = dupes.count > 0
End Function

以便您的“主要”子变为:

Sub main()
    Dim nDupes As Long
    Dim dupe As Variant
    Dim dupes As Scripting.Dictionary '<--| declare a 'Dictionary' object

    Set dupes = New Scripting.Dictionary '<--| instantiate the 'Dictionary' object
    'Calling Function
    If FindingDuplicate(ActiveSheet.UsedRange, nDupes, dupes) Then '<--| change 'ActiveSheet.UsedRange' to whatever range you want
        With dupes
            For Each dupe In .keys
                MsgBox "duplicate cell value (" & dupe & ") is duplicated " & .Item(dupe) & " times"
            Next
        End With
    Else
        MsgBox " Data Validation Completed. No Duplicate Found."
    End If    
End Sub

答案 2 :(得分:0)

您可以尝试使用Dictionary

首先,循环您的工作表(“SheetName”),而不是ActiveSheet,找到所有唯一值(没有空单元格),并将它们存储在Dictionary

之后,循环遍历Dictionary.Keys,并根据每个唯一键搜索您的范围,以查看存在多少重复项(如果要显示范围内的所有重复值)。

我稍微修改了您的Function,因此它将返回重复数量,然后返回main Sub,如果counter > 1则显示“重复”{{1在Range中发现了多少次。

代码

MsgBox