Excel VBA to count and print distinct values

前端 未结 2 394
忘了有多久
忘了有多久 2020-12-09 22:59

I have to count number of distinct values from a column and print it with the distinct value and count in another sheet. I am working with this piece of code, but for some r

2条回答
  •  旧巷少年郎
    2020-12-09 23:58

    Not the prettiest or most optimum route but it'll get the job done and I'm pretty sure you can understand it:

    Option Explicit
    
    Sub TestCount()
    
    Dim rngCell As Range
    Dim arrWords() As String, arrCounts() As Integer
    Dim bExists As Boolean
    Dim i As Integer, j As Integer
    
    ReDim arrWords(0)
    
    For Each rngCell In ThisWorkbook.Sheets("Sheet1").Range("A1:A20")
        bExists = False
    
        If rngCell <> "" Then
            For i = 0 To UBound(arrWords)
                If arrWords(i) = rngCell.Value Then
                    bExists = True
                    arrCounts(i) = arrCounts(i) + 1
                End If
            Next i
    
            If bExists = False Then
                ReDim Preserve arrWords(j)
                ReDim Preserve arrCounts(j)
    
                arrWords(j) = rngCell.Value
                arrCounts(j) = 1
    
                j = j + 1
            End If
        End If
    Next
    
    For i = LBound(arrWords) To UBound(arrWords)
        Debug.Print arrWords(i) & ", " & arrCounts(i)
    Next i
    
    End Sub
    

    This will loop through A1:A20 on "Sheet1". If the cell is not blank it will check to see if the word exists in the array. If not then it adds it to the array with a count of 1. If it does exist then it simply adds 1 to the count. I hope this suits your needs.

    Also, just something to keep in mind after glancing at your code: you should virtually NEVER use On Error Resume Next.

提交回复
热议问题