annepic
annepic

Reputation: 1387

store word content in variable

How do I copy the entire content (approx 2 pages) of a Word document in VBA and store in a variable?

I keep trying several things, none of which works:

Dim mainData As String
ThisDocument.Activate
ActiveDocument.WholeStory 'error on this line
mainData = Selection.Text

With 'record macro' I can simulate selecting a piece or the entire text, but I can't simulate storing that into a variable.

The above code throws

'This command is not available because no document is open',

but hadn't I first activated this (the current) document, and then selected it (ActiveDocument.WholeStory)? Why doesn't this work?

Later edit: I managed to do the selection like this:

Dim sText As String
Application.Selection.ClearFormatting
Application.Selection.WholeStory
sText = Application.Selection.Text
MsgBox sText

but the problem is I can't store the entire text (2 pages) in a variable. Part of it is truncated. Would you know how to store word by word (I only need a word at a time anyway)?

Later edit. I applied strReverse on the text to find out the text is actually stored entirely in the variable, just not fully displayed in the message box.

Upvotes: 3

Views: 6477

Answers (2)

Cindy Meister
Cindy Meister

Reputation: 25663

Don't use ThisDocument in code, unless you specifically want to address the file in which the code is stored and running. ThisDocument is the "code name" of that file.

Instead, use ActiveDocument to mean the document currently active in the Word window.

An addition, if you want the Selection in the currently active document, there's no reason to activate it - it's already active.

So to get the entire document content in a string

Dim mainData As String
mainData = ActiveDocument.Content.Text

where Content returns the entire main body's text as a Range object.

Note: The MsgBox has an upper character limit. If you're working with long text strings and want to see what they hold the following has more (but not "infinite") capacity:

Debug.Print mainData

Upvotes: 4

macropod
macropod

Reputation: 13490

All you need is:

Dim mainData As String
mainData = ActiveDocument.Range.Text

Upvotes: 2

Related Questions