office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

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

access excel vba獲取數組中的眾數

2020-04-02 08:00:00
tmtony8
原創
290
在數據查詢中,我們有時需要找出一組數據中出現次數最多的數字。這個也是我們常說的眾數了。

如在數組{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

    分享
    北京十一选五基本走势