Aileen
Aileen

Reputation: 11

Batch add formatted autocorrects with VBA in Word

I use a long Excel spreadsheet containing incorrect and correct terms to check consistency between documents (e.g. anti-citrullinated is always hyphenated). I've added quite a few of these as autocorrect entries via the AutoCorrect Options feature in Word but it's time-consuming .

I came across the following code that will add long lists of autocorrects.

Sub BatchAddAutoCorrectEntries()
    Dim objTable As Table
    Dim objOriginalWord As Cell
    Dim objOriginalWordRange As Range
    Dim objReplaceWordRange As Range
    Dim nRowNumber As Integer
 
    Set objTable = ActiveDocument.Tables(1)
    nRowNumber = 1
    For Each objOriginalWord In objTable.Columns(1).Cells
        Set objOriginalWordRange = objOriginalWord.Range
        objOriginalWordRange.MoveEnd Unit:=wdCharacter, Count:=-1
        Set objReplaceWordRange = objTable.Cell(nRowNumber, 2).Range
        objReplaceWordRange.MoveEnd Unit:=wdCharacter, Count:=-1
 
        AutoCorrect.Entries.Add Name:=objOriginalWordRange.Text, Value:=objReplaceWordRange.Text
 
        nRowNumber = nRowNumber + 1
    Next objOriginalWord
 
    MsgBox ("All autocorrect items in the table1 are added.")
End Sub

It doesn't preserve any formatting: super- or subscripts, etc. Formatting autocorrect entries are stored in the Normal.dotm file and not in the regular .acl file so I haven't been able to figure out a way around this.

In a similar post, someone suggested a Find and Replace macro but Find and Replace doesn't allow me to replace with super- or subscripts.

Upvotes: 1

Views: 873

Answers (4)

jeremyjcobb
jeremyjcobb

Reputation: 1

The parameters for the .AddRichText method are Name and Range--not Name and Value, as with the .Add method. See https://learn.microsoft.com/en-us/office/vba/api/word.autocorrectentries.addrichtext.

Upvotes: 0

S Ramakrishnan
S Ramakrishnan

Reputation: 1

The program is not working. It is giving an error message

Compile Error Expected Function or Variable

It is showing the following line as error

Autocorrect.Entries.Add Name:=objOriginalWordRange.Text, Value:=objReplaceWordRange.Text

Upvotes: 0

Niels
Niels

Reputation: 1

If the problem is just sub/superscribt, then you could use uni-codes. Those are also available in autocorrect. Fx writing the unicodes ₁₂₃₄₅₆₇₈₉ instead of using formating on a normal 2. Most (but not all) characters exist in super and sub unicode.

Upvotes: 0

Timothy Rylatt
Timothy Rylatt

Reputation: 7850

There are two methods of adding Auto Correct Entries, Add and AddRichText. It is this second one that you use for formatted entries.

When faced with an issue like this my first resort is to check the Object Brower in the VBA editor (press F2 to display) to see what methods and properties may be available. My next step is to look them up in the VBA technical reference, aka Help, to check the usage.

Upvotes: 1

Related Questions