store word content in variable - 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.

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

All you need is:
Dim mainData As String
mainData = ActiveDocument.Range.Text

Related

Issue with pdf docs not showing up

We recently wrote some code for a client using the Aspose.pdf library, on my system the pdf in question opened fine and most of the merge fields were filled in (we don't have the exact list of merge fields that they do).
They're telling me that on their system, some documents take 2-4 mins to open while others don't open at all.
What could be a possible cause of the document not opening at all?
My code is below:
' Load form
Dim doc As Aspose.Pdf.Document = New Aspose.Pdf.Document(sTemplateDir & sDocName)
'Get names of form fields
Dim fields As Aspose.Pdf.InteractiveFeatures.Forms.Field() = doc.Form.Fields
Dim sField As String
Dim field As Aspose.Pdf.InteractiveFeatures.Forms.Field
If fields.Length > 0 Then
For Each field In fields
'Get name of field
sField = field.FullName
'If the merge field isn't valid then we'll just leave it and assume its a fill-in
If nMergeCol.Contains(sField) And Not IsNothing(sField) Then
field.Value = nMergeCol.Item(sField)
End If
Next
End If
This has been resolved! As we suspected, it was a problem with the client's Javascript within the pdf file. The problem was within the calculations the absolute value was being used (name.value). Once this was switched to the relative value (this.event.value) the pdf file began behaving correctly with the AsPose code.

Accessing another word document TextBox

In my word "sheet", I have a CommandButton of which, when clicked, triggers a certain part of code which basically is about opening a second word document and inserting some informations from the current one (Document1) into the second one (Document2) TextBox.
I have String variables containing text in one word document (e.i. Document1). I am opening a second document (e.i. Document2). Then, I need to reach a specific TextBox from the Document2 and insert into it the value of one of the String variables I already have.
That being said, I can't access that second document (Document2) since I always gets the "4160 error" which result of the file name being incorrect.
Therefore, how can I access my second document (Document2) TextBox and insert into it a specific value I already have?
My code as follow (simplified to one variable since it'll be the same for every other):
Private Sub btn1_Click()
Dim strFile As String
Dim WordApp As New Word.Application
Dim WordDoc As Word.Document
Dim name As String
strFile = "C:\Users\WhateverUser\Desktop\WhateverFolder\Document2.docx"
name= txtBoxName.Text
'This comes from the first document (Document1) which is correct.
' Opening another Word document (Document2)
Set WordDoc = WordApp.Documents.Open(strFile)
WordApp.Visible = True
'Here is the problem
'Trying to access the Document2 TextBox (txtBoxNameDoc2) with various ways but I always get the Incorrect File Name Error
'First I tried
Documents("Document2.docx").Bookmarks("txtBoxNameDoc2").Range.Text = name
'Then I tried
Documents("Document2.docx").txtBoxNameDoc2.Text = name
'And after those, I went looking on internet and tried what I could find but none did work.
End Sub
I can speculate at some errors in the coding you have provided above, but if this line works without returning an error:
Set WordDoc = WordApp.Documents.Open(strFile)
WordApp.Visible = True
THen you should be able to do:
WordDoc.Bookmarks(txtBoxNameDoc2).Range.Text = name
This is because you have already opened "Document2.docx" and furthermore you have specifically assigned it to the WordDoc object variable. Because you have done this, you do not need to explicitly reference it from the Documents collection, as you are doing in your original code.
NB: This assumes that txtBoxNameDoc2 is valid string that identifies a bookmark in the WordDoc document. If it should be interpreted as a literal string (i.e., it is the actual name of the bookmark, then you need to qualify it with quotation marks, like:
WordDoc.Bookmarks("txtBoxNameDoc2").Range.Text = name
If this continues to raise an error, then the named bookmark doesn't exist.
It is possible to assign a bookmark to a TextBox object. Bookmarks do not "automatically" exist in a document, so first you have to ensure such a bookmark exists. You can review these and assign them (if they do not exist) through the ribbon).
Bookmarks don't exist unless you create them. You've assumed that the object's name can also refer to a Bookmark, and while it can, first you need to create the bookmark and assign it the name by which you want to refer it.

InputBox in Word 2010 VBA

I'd like to add code to my template where the macro asks "What page is the table on?" and the user can type in the response, i.e., 38. Afterward, the text, "[Table Page 38]" is inserted, one after the other, into the same, specified Word document.
Dim strPageInfo As String
strPageInfo = InputBox("Type page number for table placeholder.")
Any help would be greatly appreciated.
The following snippet will just insert the input number into the text selection. I am not sure if this is exactly what you are looking for.
Dim strPageInfo As String
strPageInfo = InputBox("Type page number for table placeholder.")
Selection.TypeText Text:="[Table Page " + strPageInfo + "]";
Here's a list of macros for your reference as well. You may be able to find exactly what you are needing to do if this doesn't work.
http://wordribbon.tips.net/C0694_Macros.html

Creating cross-references in VBA but losing formatting on save

I'm creating a word document from scratch as an OLE object via VBA, and have created cross-references in it. I am actually using LotusScript, but the principles of VBA should apply.
Once I have created the cross-reference, I format the entire table cell that contains it (Arial 8 Italic), but when the document is saved, the field updates its format. I know that I can set a property of the field manually by ticking the "Preserve formatting during updates " option in the Word front-end, but is there a VBA property for that?
NB, The cross-reference is to a heading, and the formatting I'm getting appears to be the same as that heading, which is not what I want.
Many thanks,
Phil
I found the solution :-)
This is LotusScript, but I'm sure VB users can work out what it means. Also, I call a function and 3 subroutines, which are all self-explanatory. rg is a Range, in which I've just created the cross-reference. Due to the nature off the application, I know that the field is the first one in the range. The final line is the important one.
Set rg = getTableCell(subTable, 2, 1).Range
Dim fld As Variant
Set fld = rg.Fields(1)
Call SetItalicsOnOff(rg, True)
Call SetFontFace(rg, "Arial")
Call SetFontSize(rg, 8)
fld.Code.Text = fld.Code.Text & " \* MERGEFORMAT"

Foreign characters show up as ????? in VBA 2003, how to set up UTF-8?

I have a Database in Access 2003 that needs to work with foreign language characters. The characters show up fine in the table. However, when VBA tries to read them it cannot do it.
As an example, the column ANSWER_TEXT from cf_Answer displays: 佛吉尼亞海灘
But a select statement in VBA:
sqlstmt = "SELECT ANSWER_TEXT AS ans_text FROM cf_Answer"
Set rst_a = dbs.OpenRecordset(sqlstmt, dbOpenSnapshot)
rst_a![ans_text] returns ??????.
I know this has something to do with UTF-8 encoding but I cannot find a way to set it. Is there a way to set it in the table? Currently, ANSWER_TEXT is of datatype memo. Or perhaps there is a way to set VBA to understand those characters?
Can anyone at least point me in the right direction?
The issue may be due to where you're displaying that unicode text.
I pasted those same characters into a text field in my table. Retrieving them with DLookup in the Immediate window causes them to be displayed as question marks because the Immediate window does not display unicode as you wish.
? DLookup("some_text", "tblFoo", "id = 1")
??????
A MsgBox also displays them as question marks.
MsgBox DLookup("some_text", "tblFoo", "id = 1")
However a form text box control does have the capability to handle unicode properly. Binding the text box to the field which contains those characters gives me this ...
A query can also reference unicode characters, and this uses one in its WHERE clause and displays them all correctly when the query is opened in Datasheet View.
SELECT f.id, f.some_text
FROM tblFoo AS f
WHERE (((f.some_text) Like '佛*'));
I suspect this all comes down to how you're trying to use those unicode characters and where you're displaying them.
In a comment, you stated writing those unicode characters to a text file would produce only question marks. However, if you write unicode to a text file (as in the procedure below) and display the file in an editor which is capable of handling unicode correctly, you will see the same characters you see in Datasheet View of the table where they are stored. This screenshot shows Wordpad opened with the file which was created from the code below.
Dim objFso As Scripting.FileSystemObject
Dim objFile As Scripting.TextStream
Set objFso = New Scripting.FileSystemObject
Set objFile = objFso.OpenTextFile(CurrentProject.Path & _
Chr(92) & "unicode.txt", ForWriting, True, TristateTrue)
objFile.Write DLookup("some_text", "tblFoo", "id = 1")
objFile.Close
Set objFile = Nothing
Set objFso = Nothing