获取元素出现在数组中的次数

时间:2019-04-18 12:29:28

标签: excel vba

如何计算元素出现在数组中的次数?

例如水果(香蕉,橙子,苹果,橙子,苹果,橙子)

我想得到:     香蕉(1)     橙色(3)     苹果(2)

我已经尝试过了:

/tmp % gcc -pedantic -Wall -Wextra o.c
/tmp % ./a.out
Enter first number: 12
Enter second number: 34
What kind of operation do you want to make? Type Sum, Sub, Mul or Div: aze
This command does not apply, please type the correct option
What kind of operation do you want to make? Type Sum, Sub, Mul or Div: Sum
12+34=46
/tmp % ./a.out
Enter first number: aze
invalid number
/tmp %

2 个答案:

答案 0 :(得分:4)

尝试一下

Sub test()
    fruitArr = Array("banana", "orange", "apple", "orange", "apple", "orange")
    Set dict = CreateObject("Scripting.Dictionary")
    For Each Fruit In fruitArr
        sKey = Fruit
            If Not dict.Exists(sKey) Then
                dict.Add sKey, 1
            Else
                dict(sKey) = dict(sKey) + 1
            End If
    Next Fruit
    For Each key In dict.Keys
        Debug.Print key, dict(key)
    Next key
End Sub

答案 1 :(得分:0)

尝试:

Option Explicit

Sub test()

    Dim fruits As Variant
    Dim i As Long, y As Long, count As Long, LastRow As Long

    fruits = Array("banana", "orange", "apple", "orange", "apple", "orange")

    For i = LBound(fruits) To UBound(fruits)

        count = 0

        For y = LBound(fruits) To UBound(fruits)

            If fruits(i) = fruits(y) Then

                count = count + 1

            End If

        Next y

        With ThisWorkbook.Worksheets("Sheet1")

            LastRow = .Cells(.Rows.count, "A").End(xlUp).Row

            If Application.WorksheetFunction.CountIf(.Range("A2:A" & LastRow), fruits(i)) = 0 Then
                .Range("A" & LastRow + 1).Value = fruits(i)
                .Range("B" & LastRow + 1).Value = count
            End If

        End With

    Next i

End Sub

结果(表格1,A和B列):

enter image description here