PDA

View Full Version : Access VBA to Write Hidden Text to Word Document



stepterr
05-13-2019, 01:46 PM
I'm using Access to loop through records and write to a Word document using CreateObject("Word.Application"). That is all working out well and now I'm attempting to apply formatting. I decided to have it utilize a template when I'm adding the document.


set doc = .Documents.Add("MyTestTemplate.dotx")

This is doing exactly what I want so I have my margins, font, font size, etc. all set automatically.

The word files that I'm creating need to contain hidden text being used for tagging that will be needed in a system that these files are being uploaded into. The hidden text is on the same line as text that needs to be visible and I'm struggling with how to do that all in one line as I'm writing to the Word document.

For instance, in my example below "{HSTLA}", "{HSTRA}", "{HSTLB}" and "{HSTRB}" should not be visible when I open the Word document.


{HSTLA}Sample text line 1 here that is visible in the file{HSTRA}
{HSTLB}Sample text line 2 here that is visible in the file{HSTRB}


The examples that I'm finding are applying the hidden text to a full section instead of pieces of one line and I'm lost how to apply it to my situation. Any help would be greatly appreciated!

Artik
05-18-2019, 09:37 PM
Show the code snippet by which you enter the text into the document. I'm particularly interested in how you enter the markers {HSTLA},{HSTRA} etc.

Artik

macropod
05-19-2019, 12:48 AM
The simplest approach is to write all the content as plain text, then use Word's Find/Replace function to change your tags to hidden text. For example, with Word VBA:

With ActiveDocument.Range
With .Find
.Format = True
.Forward = True
.ClearFormatting
.Replacement.ClearFormatting
.Text = "\{HST[LR][A-Z]\}"
.Replacement.Text = "^&"
.Replacement.Font.Hidden = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
End With
The above allows for the last character in your tags to be anything from A to Z.

Whether you'll see the hidden text when you open the document depends on how you have Word configured - the setting isn't document-specific.