Find text inside a Word document Text Box from VB

Help please;
I am building a Visual Basic 6 application that prints vouchers from MS Word 2000.
I have built a word template document that looks like the voucher, with marker text in the places of details that will change from voucher to voucher, such as amount and expiry date. my intention is to open this word document from vb, find and replace the amount and expiry tags with the required text, print the document and discard the changes.
This works fine except for one thing. the expiry tag is in a Text Box on the word document (to anchor its position) and the vb code I am using fails to find it.
How do I find text inside a Word document Text Box from VB?
TIA

   Dim appWord As Word.Application
   Dim oDoc As Word.Document
   Const wdReadOnly = True
   Const wdNoSave = False

   Set appWord = New Word.Application
   Set oDoc = appWord.ActiveDocument
   appWord.Documents.Open "C:\VoucherTemplate.Doc", , wdReadOnly

   'Amount
   With appWord.Selection.Find
      .Text = "%AMNT%"
      .Replacement.Text = lblValue.Caption
      .Execute Replace:=wdReplaceOne, Forward:=True, _
         Wrap:=wdFindContinue
   End With
   
   'Expiry Date
   With appWord.Selection.Find
      .Text = "%EXPIRY%"
      .Replacement.Text = lblExpiry.Caption
      .Execute Replace:=wdReplaceOne, Forward:=True, _
         Wrap:=wdFindContinue
   End With
   
   'Print out the result
   oDoc.PrintOut
   
   'Clean up
   oDoc.Close wdNoSave
   Set oDoc = Nothing
   Set appWord = Nothing
   
SpringSnowmanAsked:
Who is Participating?
 
JR2003Connect With a Mentor Commented:
Here's a couple of functions from one of my applications.
To find and replace inside a macro you need to search each StoryRange or it will just seach the basic document and not include headers, footers etc.


Private Function ReplaceText(ByVal sFindText As String, _
                             ByVal sReplaceText As String) As Boolean

    On Error GoTo Trap
   
    Dim MyRange As Object
    'Dim MyRange As Word.range 'Substitute for debugging
   
    For Each MyRange In wrdDoc.StoryRanges
        ReplaceTextInRange MyRange, sFindText, sReplaceText
    Next MyRange
   
    ReplaceText = True

    GoTo SkipTrap
   
Trap:
   
    Screen.MousePointer = vbDefault
   
    Dim iResult As VbMsgBoxResult
    With Err
        iResult = MsgBox("Error: " & .Number & vbNewLine & _
                "Description: " & .Description & vbNewLine & _
                "Source: " & .Source, vbAbortRetryIgnore Or vbExclamation, "Error")
        If iResult = vbRetry Then
            Resume
        ElseIf iResult = vbIgnore Then
            Resume Next
        End If
    End With


SkipTrap:
   
End Function


Private Function ReplaceTextInRange(MyRange As Object, _
                                    ByVal sFindText As String, _
                                    ByVal sReplaceText As String) As Boolean


    On Error GoTo Trap
   
    With MyRange
        With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = sFindText
            .Replacement.Text = sReplaceText
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            .Execute Replace:=wdReplaceAll, Forward:=True
        End With
       
        Do While Not (MyRange.NextStoryRange Is Nothing)
            Set MyRange = MyRange.NextStoryRange
            With MyRange.Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .Text = sFindText
                .Replacement.Text = sReplaceText
                .Forward = True
                .Wrap = wdFindContinue
                .Format = False
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute Replace:=wdReplaceAll, Forward:=True
            End With
        Loop
    End With
   
    ReplaceTextInRange = True

    GoTo SkipTrap
   
Trap:
   
    Screen.MousePointer = vbDefault
   
    Dim iResult As VbMsgBoxResult
    With Err
        iResult = MsgBox("Error: " & .Number & vbNewLine & _
                "Description: " & .Description & vbNewLine & _
                "Source: " & .Source, vbAbortRetryIgnore Or vbExclamation, "Error")
        If iResult = vbRetry Then
            Resume
        ElseIf iResult = vbIgnore Then
            Resume Next
        End If
    End With


SkipTrap:
   
End Function
0
 
craigewensCommented:
I do something similar to this, but instead of using the 'Selection.Find' approach i've made my word documents a template and named each of the template fields. This way i can just go to the FormFields.Item(n) and adjust it's properties there.

Here is an example of what i do... (note: i'm running this from excel and extracting the formfield items and placeing them into excel, adjusting this for your requirements would be simple enough)

[code]
Sub Test(MyPath As String, MyName As String)
    Dim nFields As Integer
    Dim n As Integer
    Dim check
    Dim FileName As String
    Dim Row As Integer
    Dim Column As Integer
    FileName = MyPath & MyName
       
    Dim WordObj As Word.Application
    Dim DoctObj As Word.Document
   
    Set WordObj = CreateObject("Word.Application")
    Set DoctObj = WordObj.Documents.Open(FileName)
    nFields = DoctObj.FormFields.Count
    If nFields >= 1 Then
        For n = 1 To nFields
            check = DoEvents
            Select Case DoctObj.FormFields.Item(n).Name
            Case Is = "SPRNumber"           'Column 1.
                Column = 1
            Case Is = "DateRaised"          'Column 2.
                Column = 2
            Case Is = "ProblemTitle"        'Column 3.
                Column = 3
            Case Is = "RelatedSPRandORs"    'Column 4.
                Column = 4
            Case Is = "ClosedOn"            'Column 5.
                Column = 5
            Case Else                       'None Of The Above.
                Column = 0
            End Select
            If Column Then Sheets("SPR Status Log").Cells(Row + 2, Column) = DoctObj.FormFields.Item(n).Result
        Next n
    End If
    DoctObj.Close
    WordObj.Quit
    Set WordObj = Nothing
End Sub
[/code]

I hope this helps in some way.
Good luck!
0
 
_agj_Commented:
a textbox in a doc would be accessible as:

oDoc.TextBox1 etc.

say u can set

oDoc.TextBox1.Text = "1"
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
_agj_Commented:
oDoc.InlineShapes("TextBox1").Text  = "1" should work
0
 
SpringSnowmanAuthor Commented:
Thanks craiqeqens, but i need to use s Word Text Box because some of the variable text above this Text Box is a variable number of lines long, and i don't want the bits that I have put in my text box to move about the page. Unless there is another way to anchor text..

_aqi_, I was not aware that Text Boxes in a MS Word document _had_ names. I am speaking here of Word Insert menu | Text  Box, then draw the text box on the document, not a VBA TextBox.
0
 
SpringSnowmanAuthor Commented:
JR2003, It looks like this would work. How do i call the ReplaceTextInRange function? ie. how do i specify the whole story as the range?
0
 
JR2003Commented:
To get the code above to work you will have to put the following variables at module level rather than procedure level.

    Dim WordObj As Word.Application
    Dim DoctObj As Word.Document

Also change wrdDoc to DoctObj in the ReplaceText function
0
 
JR2003Commented:
Just call the ReplaceText function, that calles the ReplaceTextInRange function

To call it
e.g.:

    ReplaceText "%AMNT%",lblValue.Caption
0
 
SpringSnowmanAuthor Commented:
JR2003, Thanks for that, this looks like a good answer to my question and i am awarding you the points.
For the sake of any who follow, and also need an answer to this question, there is a simpler solution. (Isn't there always?): Use Frames rather than Text Boxes to anchor the text, as the contents of these can be searched in the usual way.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.