0
votes

I'm trying to replace every 10th word in a Word document with underscores equal to the length of the word. This is the code that I've tried so far but it doesn't seem close to working. I'm new to VBA. I feel like I'm able to move between words using the FOR EACH loop but I'm having trouble working the selection object

Sub Macro1()
'
' Macro1 Macro
'
'
    i = 0
    For Each aword In ActiveDocument.Words
        ' Selection = aword
        i = i + 1
        aword.Select
        If (i Mod 10) = 0 Then

            blanks = ""
            For Counter = 0 To Len(aword)
                blanks = blanks + "_"
            Next Counter
            Word.Selection.TypeText (blanks)
            aword.Cut
        End If
    Next aword
End Sub

Also, is VBA the easiest language available for doing something like this in a word processing document? Is there a simpler one? I'm trying to help a student who last coded with Wang VS Glossary Decision Processing language https://en.wikipedia.org/wiki/Wang_Laboratories#Wang_OIS

1

1 Answers

1
votes

If you are just starting out, VBA is probably the easiest whenever you are working directly with Microsoft Office documents. The main reason is that the functionality is already embedded in the program so you can easily test your scripts from within the application.

Your code almost works once you take out aWord.Cut. Just be aware that certain things are treated as part of the Word collection that you might not expect. For instance, a comma with a space after it is treated as a "word". Same with a period. In the code below I tested for those two conditions but you may need more test depending on what your data looks like.

Lastly I needed to change your loop a bit because once you modify the collection, the iterator in the for each loop resets to what you modified. So in your example, every ninth word after the first would get changed.

i = 1
For Each aword In ActiveDocument.Words
    If (aword <> ". " And aword <> ", ") Then
        i = i + 1
        aword.Select

        If (i Mod 11) = 0 Then
            blanks = ""
            For Counter = 1 To Len(aword) - 1
                blanks = blanks + "_"
            Next Counter
            blanks = blanks + " "
            Word.Selection.TypeText (blanks)
        End If
    End If
Next aword