سؤال

I need to be able count the number of unique letters in an array such as this:

[A01, B01, C01, A02, C02]

For this example the result should be 3. Thus I need to include the value only in the case that a new letter is found.

This is being done in a Word 2007 userform. Any suggestion or example on accomplishing such a task?

هل كانت مفيدة؟

المحلول

This works for me. Run the Test() macro to obtain the result for demo data.

Function UniqueLetterCount(ByRef Values() As String) As Integer

    UniqueLetterCount = 0
    Dim LettersSeen    As String
    Dim i As Integer
    Dim Letter As String
    LettersSeen = ""

    For i = LBound(Values) To UBound(Values)
        Letter = Left(Values(i), 1)
        If InStr(LettersSeen, Letter) = 0 Then 'if Letter was not found in LettersSeen
            UniqueLetterCount = UniqueLetterCount + 1
            LettersSeen = LettersSeen & Letter
        End If
    Next

End Function


Sub Test()

    Dim DemoArray(9) As String
    DemoArray(0) = "A01"
    DemoArray(1) = "A02"
    DemoArray(2) = "B01"
    DemoArray(3) = "C01"
    DemoArray(4) = "A03"
    DemoArray(5) = "D01"
    DemoArray(6) = "D02"
    DemoArray(7) = "C02"
    DemoArray(8) = "B02"
    DemoArray(9) = "C03"
    MsgBox "Unique letter count is " & UniqueLetterCount(DemoArray)

End Sub
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top