Check if an entry exists in AutoCorrect.Entries

164 Views Asked by At

Is there an efficient way of looking up a name in the AutoCorrect.Entries for MS Word to check if it exists (before I add a new entry with that name; I have the code that adds the entry and it works but it REPLACES the entry if it exists)

Sub AutoCorrection()
'
' AutoCorrect Macro
'
'
Dim selected As Variant
Dim name As Variant

'selected text gets stored as the selected
selected = Selection

'Checking if selected text is less than 2 characters.
If Len(selected) < 2 Then
    MsgBox "Select text for autocorrect", vbOKOnly, "Nothing Selected"
    Exit Sub
End If

'Displaying the selected text and getting input for the name
name = InputBox(selected, "Name for this autocorrect?")

'*** In here, I want to check if this name exists in the entries before adding a new entry ***

AutoCorrect.Entries.AddRichText name:=name, Range:=Selection.Range
End Sub
1

There are 1 best solutions below

1
Charles Kenyon On

The following should work.

Private Function AutoCorrectEntryExist(strName As String) As Boolean
    ' Charles Kenyon 2022-06-14 Reports True if an AutoCorrect Entry uses the name given in strName
    ' https://stackoverflow.com/questions/72619065/check-if-an-entry-exists-in-autocorrect-entries/72625298#72625298
    '
    Dim oEntry As Word.AutoCorrectEntry
    For Each oEntry In AutoCorrect.Entries
        If oEntry.Name = strName Then
            MsgBox prompt:=strName & " is already in use, Choose a different name.", title:="In Use!", buttons:=vbCritical
            AutoCorrectEntryExist = True
            GoTo EntryFound
        End If
    Next oEntry
    AutoCorrectEntryExist = False
EntryFound:
    Set oEntry = Nothing
End Function

You would call it from your procedure with the name you want to use. It will report False if the name is not in use and True if it is.

If AutoCorrectEntryExist(name) = True Then
   ' code here to use if already used
End If

You could skip the msgBox in the Function. This is NOT going to be fast if you have many entries.

btw, "name" is a terrible name for your variable, IMO.