office交流網(wǎng)--QQ交流群號及微信交流群

Access培訓(xùn)群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

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

微信交流群(請用微信掃碼)

        

access excel vba獲取數(shù)組中的眾數(shù)

2020-04-02 08:00:00
tmtony8
原創(chuàng)
4634
在數(shù)據(jù)查詢中,我們有時需要找出一組數(shù)據(jù)中出現(xiàn)次數(shù)最多的數(shù)字。這個也是我們常說的眾數(shù)了。

如在數(shù)組{2,3,2,5,8,2,16,17} ,眾數(shù)即是 2了

這個我們?nèi)绻肧QL語句,是很容易求出來的。用count 統(tǒng)計,用order by 排序一下就出來結(jié)果了。


但是在VBA中,如何求出數(shù)組中的眾數(shù)呢?下面給出具體的函數(shù)

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
'    若所有數(shù)據(jù)都是眾數(shù),則沒有眾數(shù)
    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) = "沒有眾數(shù)"
        gf_mode = x
        Exit Function
    End If
'    找出所有眾數(shù)
    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

在窗體或者直接調(diào)用函數(shù),截圖如下

' 調(diào)用求眾數(shù)的函數(shù)
Public Sub acc()
    Dim arrtxt() As Double

    arrtxt = gf_mode(Array(2,3,2,5,8,2,16,17))
'    顯示所有眾數(shù)
    For i = 0 To UBound(arrtxt)
        MsgBox "眾數(shù)是:" & "" & arrtxt(i)
    Next
End Sub

    分享
    文章分類
    聯(lián)系我們
    聯(lián)系人: 王先生
    Email: 18449932@qq.com
    QQ: 18449932
    微博: officecn01
    移動訪問