Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store word content in variable

Tags:

ms-word

vba

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.

like image 583
annepic Avatar asked Jun 17 '26 17:06

annepic


2 Answers

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
like image 107
Cindy Meister Avatar answered Jun 19 '26 07:06

Cindy Meister


All you need is:

Dim mainData As String
mainData = ActiveDocument.Range.Text
like image 36
macropod Avatar answered Jun 19 '26 07:06

macropod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!