arrays - 查找数组中的重复数字vba

标签 arrays excel vba integer repeat

我试图在 vba 中创建一个大小为 50 的数组,其中包含 0 到 20 之间的随机数,然后将该数组中重复的数字提取到另一个数组中。

Sub Problem10()
Dim numbers() As Double, odd() As Double, even() As Double, five() As Double, repeating() As Double, x As Integer, i As Integer, sOdd As Integer, sEven As Integer, sFive As Integer, sNumbers As Integer, sRepeating As Integer, y As Integer, listed As Boolean
sRepeating = 0
sNumbers = 50
For i = 1 To sNumbers
    ReDim Preserve numbers(i)
    numbers(i) = Int(20 * rnd) 
    'find repeating numbers
    For x = 1 To i
        If numbers(x) = numbers(i) And i <> x Then
            'check if there are any repeated numbers already
            If sRepeating > 0 And listed = False Then
                For y = 1 To sRepeating
                   'check if the number is already listed as a repeated number
                    If numbers(i) = repeating(y) Then
                        listed = True
                    Else
                        sRepeating = sRepeating + 1
                        ReDim Preserve repeating(sRepeating)
                            repeating(sRepeating) = numbers(i)
                            Cells(sRepeating + 1, 4).Value = repeating(sRepeating)
                            listed = True
                    End If
                Next y
            End If
        End If
    Next x
    Cells(i + 1, 5).Value = numbers(i)
Next i
End Sub

我能够使用随机数 (numbers()) 创建数组,然后提取包含偶数、奇数和 5 的倍数的新数组。但是,我不知道如何仅提取重复的数字。 目前,这仅找到第一个重复数字,而没有找到其他数字。

最佳答案

考虑下面的例子:

Option Explicit

Sub Test()

    Dim i
    Dim numbers(0 To 49)
    Dim repeating()
    Dim q

    ' Fill array with random numers
    Randomize
    For i = 0 To 49
        numbers(i) = Int(20 * Rnd)
    Next

    ' Filter repeating elements
    With CreateObject("Scripting.Dictionary")
        ' Count each number qty
        For i = 0 To 49
            .Item(numbers(i)) = .Item(numbers(i)) + 1
        Next
        ' Remove non-repeating
        For Each q In .Keys()
            If .Item(q) = 1 Then .Remove q
        Next
        ' Retrieve array
        repeating = .Keys()
    End With

    Debug.Print Join(numbers)
    Debug.Print Join(repeating)

End Sub

关于arrays - 查找数组中的重复数字vba,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42540978/

相关文章:

python - 如何根据 python 列表中的索引进行多个多项目替换?

excel - 到不同工作簿和特定工作表的超链接?

r - Excel VBA 和 R : batch mode vs interactive mode

excel - 如何从 5 个不同范围中仅获取唯一值并删除重复值?

java - 序列化整数[]

java - 字符串数组中的通配符替换

c# - 通过打开 Excel 窗口将数据从 C# 写入 Excel 中断

excel - 获取多个规模不同的组的组平均值

ms-access - 确定路径是否为网络路径 VBA

java - 字符串到字节然后 byte[] 0xformat