Looping in word vba

I know how to get every paragraph in a word document. But I am looking for a way to loop through each word in a MS Word document.

Sub Sample()

Dim apara As Paragraph
Dim lineText As String

For Each apara In ActiveDocument.Paragraphs

     lineText = apara.Range

     'Now print the paragraph 

     Debug.Print lineText 

Next apara

End Sub

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Mar 28, 2014 at 11:06

Kamran's user avatar

1

For Each sentence In ActiveDocument.StoryRanges
    For Each w In sentence.Words
        Debug.Print w
    Next
Next

answered Mar 28, 2014 at 13:16

Aidan's user avatar

AidanAidan

1,5401 gold badge13 silver badges20 bronze badges

0

Here’s another, very similar solution which may be helpful for others. The accepted answer grabs every single word in the document including header, footer, etc., whereas this answer will only grab the words in the «main» area of the document.

For Each para In ActiveDocument.Paragraphs
    For Each wrd In para.Range.Words
        Debug.Print wrd
    Next wrd
Next para

answered Oct 31, 2018 at 17:24

Marcucciboy2's user avatar

Marcucciboy2Marcucciboy2

3,1483 gold badges19 silver badges38 bronze badges

In the first post in this series, we described VBA for Word and how it could be useful to writers. In this part, we delve into VBA and explore some basic tasks:

  • Getting started
  • Writing text to a document
  • Reading text from a document
  • Looping through all the paragraphs in a document

Getting Started

There are three things you need to do to start using VBA:

  • Open the VBA Editor – Create a blank document in Word and press Alt+F11. The Microsoft Visual Basic for Applications window (the VBA Editor) opens. It may seem intimidating at first, but don’t be discouraged — it is much easier than you think!
  • Create a Placeholder (Module) for Your Code – In the VBA Editor, on the left, you see two top-level folders called Normal and Project (Document1). Normal is the template that most Word documents are based on by default; you can ignore it in this context. Project (Document1) is the blank document that you just created. This is where you add your code.To do that, you must create a placeholder into which you can put your code. This placeholder is known as a Module. Right-click Project (Document1) and choose Insert Module. A new Module1 (Code) window opens. You’re ready to add some code.
  • Create a Subroutine – In Word VBA, the simplest way to perform a task is to use a subroutine. Create a subroutine by typing Sub <Name>, where <Name> can be anything other than the few reserved keywords that VBA uses. Typically, you choose a name that closely relates to the task you want to perform as demonstrated in the following examples.

Writing Text to a Document

Writing text is a fundamental task you will need in almost any macro. For example, let’s say you want to get text from a different source (another Word document, an Excel document, or even a web page). Once you acquire the text, you will need to write it into your document. This section demonstrates one easy method you can use to write text.

Let’s create a subroutine called WriteText.

Note that when you type Sub WriteText and press Return, the VBA editor automatically adds an End Sub statement, which is the statement required to close the subroutine. This auto-complete feature is very helpful (as you will discover).

On the blank line between the Sub WriteText() and the End Sub statements, press Tab, then type:
Selection.InsertAfter («Hello World!»)

So your complete code looks like this:

Sub WriteText() 
    Selection.InsertAfter ("Hello World!")
End Sub

Note that once you’ve typed Selection., the editor displays a drop-down list with possible alternatives. This is a feature that Microsoft calls IntelliSense. It helps you avoid spelling and syntax errors.

Now, with the cursor inside the subroutine, click (Run Sub/UserForm) on the toolbar. Alternatively, from the menu, choose Run > Run Sub/User Form.

Result: The script writes the text ‘Hello World!’ into Document1.

Congratulations! You have just created and run your first Word VBA macro. I think you’ll agree that it’s not too difficult.

A few things to note:

  • Selection is a VBA object that represents whatever is selected at the time it is used. If nothing is selected, it represents the position of the cursor.
  • InsertAfter is a method of the Selection object that inserts whatever text you specify after the selection.
  • The method’s parameter (in parentheses) is the actual text that will be inserted. The double quotes tell VBA that you want to insert the string of text between them.

OK, so now you know how to write text into a Word document at the position of the cursor. Let’s save the document before we proceed.

In the VBA editor, choose File > Save As, and in the Save As dialog, select Word Macro-Enabled Document as the file type. This is a special format for documents that contain macros. Use ‘Hello World’ as the file name and press the Save button.

Reading Text from a Document

Reading text is a another fundamental task you will need in many macros. For example, you may want to read the text in the third paragraph of multiple documents for some specific reason. This section demonstrates a simple way to read text.

Continuing with your Hello World document, add the following lines of text so that you have something to read:

Apples
Oranges
Mary had a little lamb.

Now you have four paragraphs in your document. Let’s create a small VBA macro to read the third paragraph. In the VBA window, type the following text after your WriteText() subroutine:

Sub ReadText()
    MsgBox (ActiveDocument.Paragraphs(3).Range.Text)
End Sub 

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: A dialog box containing the word ‘Oranges’ pops up. This is the text in paragraph 3.

That’s it! You have programmatically read some text from the Word document. Using this macro, you can read the third paragraph of any Word file. Once again, surprisingly easy!

A few things to note:

  • MsgBox() is an easy way to display the values of items. It is really useful for debugging. In this example, you use it to show the text content of paragraph 3.
  • ActiveDocument is the currently active document, in this case the Hello World document you saved.
  • Paragraphs is a collection (or group) of all the paragraphs in the active document. You want the third element in that collection, so you can write the notation Paragraphs(3).
  • Range.Text represents the text of the paragraph.

The text of the paragraph is not the only thing you can read. For example, you can read the style of the paragraph. Add a second line (highlighted) to your macro as shown:

Sub ReadText()
    MsgBox (ActiveDocument.Paragraphs(3).Range.Text)
    MsgBox (ActiveDocument.Paragraphs(3).Style) 
End Sub

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: The dialog box pops up twice. The first time, it contains ‘Oranges’ as before. The second time, it contains ‘Normal’, which is the name of the style associated with the paragraph.

Looping Through All the Paragraphs in a Document

Another task that is often necessary is to loop through all the paragraphs in a document. For example, you may want to look at each paragraph for some style or characteristic. In VBA, it is easy to loop through the paragraphs in a document.

Type the following code in the VBA editor window:

Sub LoopThroughParas()
    For Each para In ActiveDocument.Paragraphs
        MsgBox (para.Range.Text)
    Next para
End Sub

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: The dialog box pops up four times with the content of each paragraph.

A few things to note:

  • For … Next is the VBA statement combination that does the looping.
  • ActiveDocument.Paragraphs is the collection of all the paragraphs in the active document.
  • para is a variable that represents one paragraph.
  • para.Range.Text is the content of the paragraph. This changes on each loop, as a different paragraph is examined each time.
  • MsgBox pops up the dialog box each time through the loop.

So with five short lines of code we can loop through every paragraph in the document, including paragraphs in tables. This works regardless of the size of the document. You could apply this macro to a document that is several hundred pages long. However, that would not be wise, because a dialog box would pop up for each and every paragraph. That would be a lot of dialog boxes to respond to.

Fortunately, there is another way to display output. Instead of using the MsgBox line, you can use Debug.Print <something>. The result is displayed in the Immediate window (if it’s not already visible in the VBA editor, choose View > Immediate window).

Replace the MsgBox line with Debug.Print para.Range.Text in your code as highlighted in the following code snippet:

Sub LoopThroughParas()
    For Each para In ActiveDocument.Paragraphs
        Debug.Print para.Range.Text 
    Next para
End Sub

With the cursor inside the subroutine, click  (Run Sub/UserForm) on the toolbar.

Result: The content of each paragraph is now written to the Immediate window.

Have you encountered situations where you needed to check through a document paragraph by paragraph for some reason? Do you think VBA could have helped? Let us know.

In the next post, we build on the basic skills learned here and look at some more practical applications for VBA.

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Loops In Word

Loops In Word

(OP)

31 Aug 03 11:51

Ive just started mucking about with VBA for Word and decided to do a module that would go through a Word document and reverse all the words in that doc ie Tek-Tips becomes spiT-keT (I was bored!) I dont have the code to hand as it was at work however the basis is:

Get number of words in document, loop from 1 to that number, using Selection. get the word (and store in string WordIn) and then loop from the number of letters in the word to 1, each time taking the relevant letter (using MID) and appending it to a String called WordOut before replacing the selection with WordOut.

Everything works fine until the number of characters gets to about 500 and then it stops. Ive debugged, nothing seems out of the ordinary. I dont get an error message or anything else. Ive tried using different variable types for my counters (Single, Double, Integer) but no difference.

Any thoughts?

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Like this post? Please share to your friends:
  • Loop excel что это
  • Look at the underlined word and complete the plan alexander borodin
  • Look at the table then choose the correct word in sentences 1 and 2
  • Loop excel rows vba
  • Lookups in excel 2007