# Compile Error Syntax Error when running macro on word



## Confusedword (May 4, 2014)

Hi Guys,

I am attempting to run the code below on word for mac. When I do I get a "compile error syntax error" error box.

I was wondering if anyone knew what the problem is? This is word 2011 for mac.

_______

Sub WordFrequency()


Dim SingleWord As String 'Raw word pulled from doc
Const maxwords = 9000 'Maximum unique words
allowed Dim Words(maxwords) As String 'Array to hold
unique words Dim Freq(maxwords) As Integer 'Frequency
counter for Unique Words
Dim WordNum As Integer 'Number of unique words
Dim ByFreq As Boolean 'Flag for sorting order
Dim ttlwds As Long 'Total words in the
document Dim Excludes As String 'Words to be
excluded Dim Found As Boolean 'Temporary flag
Dim j, k, l, Temp As Integer 'Temporary variables
Dim tword As String '


' Set up excluded words
' Excludes =
"[the][a][of][is][to][for][this][that][by][be][and][are]"
Excludes = ""
Excludes = InputBox$("Enter words that you wish to exclude,
surrounding each word with [ ].", "Excluded Words", "")
' Excludes = Excludes & InputBox$("The following words are
excluded: " & Excludes & ". Enter words that you wish to exclude,
surrounding each 'word with [ ].", "Excluded Words", "")
' Find out how to sort
ByFreq = True
Ans = InputBox$("Sort by WORD or by FREQ?", "Sort order",
"FREQ") If Ans = "" Then End
If UCase(Ans) = "WORD" Then
ByFreq = False
End If


Selection.HomeKey Unit:=wdStory
System.Cursor = wdCursorWait
WordNum = 0
ttlwds = ActiveDocument.Words.Count
Totalwords = ActiveDocument.Words.Count


' Control the repeat
For Each aword In ActiveDocument.Words
SingleWord = Trim(aword)
If SingleWord "A" Or SingleWord "z" Then SingleWord =
"" 'Out of range?
If InStr(Excludes, "[" & SingleWord & "]") Then
SingleWord = "" 'On exclude list?
If Len(SingleWord) 0 Then
Found = False
For j = 1 To WordNum
If Words(j) = SingleWord Then
Freq(j) = Freq(j) + 1
Found = True
Exit For
End If
Next j
If Not Found Then
WordNum = WordNum + 1
Words(WordNum) = SingleWord
Freq(WordNum) = 1
End If
If WordNum maxwords - 1 Then
j = MsgBox("The maximum array size has been
exceeded. Increase maxwords.", vbOKOnly)
Exit For
End If
End If
ttlwds = ttlwds - 1
StatusBar = "Remaining: " & ttlwds & " Unique: " &
WordNum Next aword


' Now sort it into word order
For j = 1 To WordNum - 1
k = j
For l = j + 1 To WordNum
If (Not ByFreq And Words(l) Words(k)) Or (ByFreq And
Freq(l) Freq(k)) Then k = l
Next l
If k j Then
tword = Words(j)
Words(j) = Words(k)
Words(k) = tword
Temp = Freq(j)
Freq(j) = Freq(k)
Freq(k) = Temp
End If
StatusBar = "Sorting: " & WordNum - j
Next j


' Now write out the results
tmpName = ActiveDocument.AttachedTemplate.FullName
Documents.Add Template:=tmpName, NewTemplate:=False
Selection.ParagraphFormat.TabStops.ClearAll
With Selection
For j = 1 To WordNum
.TypeText Text:=Words(j) & vbTab & Trim(Str(Freq(j)))
& vbCrLf
Next j
End With
ActiveDocument.Range.Select
Selection.ConvertToTable
Selection.Collapse wdCollapseStart
ActiveDocument.Tables(1).Rows.Add BeforeRow:=Selection.Rows(1)
ActiveDocument.Tables(1).Cell(1, 1).Range.InsertBefore "Word"
ActiveDocument.Tables(1).Cell(1, 2).Range.InsertBefore
"Occurrences"
ActiveDocument.Tables(1).Range.ParagraphFormat.Ali gnment =
wdAlignParagraphCenter
ActiveDocument.Tables(1).Rows.Add
ActiveDocument.Tables(1).Cell(ActiveDocument.Table s(1).Rows.Count,
1).Range.InsertBefore "Total words in Document"
ActiveDocument.Tables(1).Cell(ActiveDocument.Table s(1).Rows.Count,
2).Range.InsertBefore Totalwords
ActiveDocument.Tables(1).Rows.Add
ActiveDocument.Tables(1).Cell(ActiveDocument.Table s(1).Rows.Count,
1).Range.InsertBefore "Number of different words in Document"
ActiveDocument.Tables(1).Cell(ActiveDocument.Table s(1).Rows.Count,
2).Range.InsertBefore Trim(Str(WordNum)) System.Cursor =
wdCursorNormal ' j = MsgBox("There were " & Trim(Str(WordNum))
& " different words ", vbOKOnly, "Finished")
Selection.HomeKey wdStory


End Sub

____________

Thanks for your help and I hope you're well!


----------



## Macropod (May 4, 2014)

The code you've posted has evidently been copied from somewhere else and the copy/paste process has made a complete mess of it. Variable declarations that should start on new lines have been wrapped into preceding lines, comments have thereby been broken so that they begin new lines, required '=' expressions have been lost, and so on.

I gather you want to generate a concordance/frequency count for a document. The following macro generates a list of all words used in the active document, and outputs them alphabetically sorted, with frequency and page #s of occurrence in a three-column table at the end of that document, starting on a new page. The page #s output is something your posted code doesn't support. The macro only lists words in the MainTextStory, not headers/footers/footnotes/endnotes etc. It also has an exclusion list, so that various words and phrases can be excluded. That list (defined by the comma-separated words & phrases in the StrExcl string variable) holds the words and phrases to be omitted from the concordance. Any phrases you might want to add should be inserted into the exclusions list ahead of any of the single-word exclusions (so that conflicts don’t occur).

```
Sub ConcordanceBuilder()
Application.ScreenUpdating = False
Dim StrIn As String, StrOut As String, StrTmp As String, StrExcl As String
Dim i As Long, j As Long, k As Long, l As Long, m As Long, Rng As Range
'Define the exlusions list
StrExcl = "a,am,an,and,are,as,at,b,be,but,by,c,can,cm,d,did," & _
          "do,does,e,eg,en,eq,etc,f,for,g,get,go,got,h,has,have," & _
          "he,her,him,how,i,ie,if,in,into,is,it,its,j,k,l,m,me," & _
          "mi,mm,my,n,na,nb,no,not,o,of,off,ok,on,one,or,our,out," & _
          "p,q,r,re,s,she,so,t,the,their,them,they,this,t,to,u,v," & _
          "via,vs,w,was,we,were,who,will,with,would,x,y,yd,you,your,z"
With ActiveDocument
  'Get the document's text
  StrIn = .Content.Text
  'Strip out unwanted characters. Amongst others, hyphens and formatted single quotes are retained at this stage
  For i = 1 To 255
    Select Case i
      'To strip out numbers, delete ', 58'
      Case 1 To 35, 37 to 38, 40 To 43, 45, 47, 58 To 64, 91 To 96, 123 To 127, 129 To 144, 147 To 149, 152 To 162, 164, 166 To 171, 174 To 191, 247
      StrIn = Replace(StrIn, Chr(i), " ")
    End Select
  Next
  'Delete any periods or commas at the end of a word. Formatted numbers are thus retained.
  StrIn = Replace(Replace(Replace(Replace(StrIn, Chr(44) & Chr(32), " "), Chr(44) & vbCr, " "), Chr(46) & Chr(32), " "), Chr(46) & vbCr, " ")
  'Convert smart single quotes to plain single quotes & delete any at the start/end of a word
  StrIn = Replace(Replace(Replace(Replace(StrIn, Chr(145), "'"), Chr(146), "'"), "' ", " "), " '", " ")
  'Convert to lowercase
  StrIn = " " & LCase(Trim(StrIn)) & " "
  'Process the exclusions list
  For i = 0 To UBound(Split(StrExcl, ","))
    While InStr(StrIn, " " & Split(StrExcl, ",")(i) & " ") > 0
      StrIn = Replace(StrIn, " " & Split(StrExcl, ",")(i) & " ", " ")
    Wend
  Next
  'Clean up any duplicate spaces
  While InStr(StrIn, "  ") > 0
    StrIn = Replace(StrIn, "  ", " ")
  Wend
  StrIn = " " & Trim(StrIn) & " "
  j = UBound(Split(StrIn, " "))
  l = j
  For i = 1 To j
    'Find how many occurences of each word there are in the document
    StrTmp = Split(StrIn, " ")(1)
    While InStr(StrIn, " " & StrTmp & " ") > 0
      StrIn = Replace(StrIn, " " & StrTmp & " ", " ")
    Wend
    'Calculate the number of words replaced
    k = l - UBound(Split(StrIn, " "))
    'Update the output string
    StrOut = StrOut & StrTmp & vbTab & k & vbCr
    l = UBound(Split(StrIn, " "))
    If l = 1 Then Exit For
    DoEvents
  Next
  StrIn = StrOut
  StrOut = ""
  For i = 0 To UBound(Split(StrIn, vbCr)) – 1
    m = 0
    StrTmp = ""
    With .Range
      With .Find
        .ClearFormatting
        .Text = Split(Split(StrIn, vbCr)(i), vbTab)(0)
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute
      End With
      Do While .Find.Found
        l = .Information(wdActiveEndAdjustedPageNumber)
        'Omit the If test to output the page # for every instance
        If l <> m Then
          StrTmp = StrTmp & " " & l
          m = l
        End If
        .Collapse (wdCollapseEnd)
        .Find.Execute
      Loop
    End With
    StrTmp = Replace(Trim(StrTmp), " ", ",")
    StrOut = StrOut & Split(StrIn, vbCr)(i) & vbTab & StrTmp & vbCr
  Next
  'Create the concordance table on a new last page
  Set Rng = .Range.Characters.Last
  With Rng
    .InsertAfter vbCr & Chr(12) & StrOut
    .Start = .Start + 2
    .ConvertToTable Separator:=vbTab, Numcolumns:=3
    .Tables(1).Sort Excludeheader:=False, FieldNumber:=1, _
      SortFieldType:=wdSortFieldAlphanumeric, _
      SortOrder:=wdSortOrderAscending, CaseSensitive:=False
  End With
End With
Application.ScreenUpdating = True
End Sub
```
The above code strips out trailing apostrophes, with the result that some possessive word forms may look a bit odd. Also, unless numbers are stripped out (which will impact mixed alpha-numeric strings), fields (such as noteref fields) that appear after a word will cause that word and its field number to be output separately as ‘words’ in their own right.

PS: When posting code, please use the code tags. They're on the 'Go Advanced' tab at the bottom of this screen.


----------



## BThis (Dec 14, 2021)

I realize this is ancient, but I'm trying to run Paul Edstein's code, and keep getting a "Compile Error: Syntax Error" at the line: 
For i = 0 To UBound(Split(StrIn, vbCr)) – 1 

Any suggestions for fixing this?


----------



## RoryA (Dec 15, 2021)

Replace that dash with a minus sign and it should be ok.


----------

