office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

access excel vba获取数组中的众数

2020-04-02 08:00:00
tmtony8
原创
306
在数据查询中,我们有时需要找出一组数据中出现次数最多的数字。这个也是我们常说的众数了。

如在数组{2,3,2,5,8,2,16,17} ,众数即是 2了

这个我们如果用SQL语句,是很容易求出来的。用count 统计,用order by 排序一下就出来结果了。


但是在VBA中,如何求出数组中的众数呢?下面给出具体的函数

Function gf_mode(a)
    Dim b As Integer
    Dim c() As Double
    Dim f() As Double
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    Dim x() As Double
    k = UBound(a)
    ReDim c(k), f(k)
    For i = 0 To k - 1
        If f(i) = 0 Then
            c(i) = 1
            For j = i + 1 To k
                If a(j) = a(i) Then
                    c(i) = c(i) + 1
                    f(j) = 1
                End If
            Next
        End If
    Next
    If f(i) = 0 Then c(i) = 1
    b = 1
    For i = 0 To k
        If c(i) > b Then b = c(i)
    Next
'    若所有数据都是众数,则没有众数
    For i = 0 To k
        If c(i) <> b And c(i) <> 0 Then Exit For
    Next
    If i = k + 1 Then
        ReDim x(0)
        x(0) = "没有众数"
        gf_mode = x
        Exit Function
    End If
'    找出所有众数
    j = 0
    For i = 0 To k
        If c(i) = b Then
            ReDim Preserve x(j)
            x(j) = a(i)
            j = j + 1
        End If
    Next
    gf_mode = x
End Function

在窗体或者直接调用函数,截图如下

' 调用求众数的函数
Public Sub acc()
    Dim arrtxt() As Double

    arrtxt = gf_mode(Array(2,3,2,5,8,2,16,17))
'    显示所有众数
    For i = 0 To UBound(arrtxt)
        MsgBox "众数是:" & "" & arrtxt(i)
    Next
End Sub

    分享