Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the Frequencies of Words in Excel Strings

Tags:

excel

vba

Suppose I have a column of arbitrary length where each cell contains a string of text. Is there a way to determine what words appear most frequently in the column (not knowing in advance which words to check) and subsequently order these words along with their frequencies in a two column table? Would VBA be best for this task?

As an example, a cell might contain the string "This is a string, and the # of characters inthis string is>0." (errors intentional)

like image 360
114 Avatar asked Nov 30 '22 19:11

114


1 Answers

Select a portion of column A and run this small macro ( the table will be placed in cols. B & C :

Sub Ftable()
    Dim BigString As String, I As Long, J As Long, K As Long
    BigString = ""

' Add code to sum both "All" and "all" ' Add code to separate "." "!" etc. from the word preceeding them so that word ' is also counted in the total. For example: "all." should not be reported as 1 ' "all." but "all" be added to the total count of "all" words. ' Would you publish this new code?

    For Each r In Selection 
          BigString = BigString & " " & r.Value
    Next r
    BigString = Trim(BigString)
    ary = Split(BigString, " ")
    Dim cl As Collection
    Set cl = New Collection
    For Each a In ary
        On Error Resume Next
        cl.Add a, CStr(a)
    Next a

    For I = 1 To cl.Count
        v = cl(I)
        Cells(I, "B").Value = v
        J = 0
        For Each a In ary
            If a = v Then J = J + 1
        Next a
        Cells(I, "C") = J
    Next I

End Sub
like image 139
Gary's Student Avatar answered Dec 05 '22 15:12

Gary's Student