Solved

Find text inside a Word document Text Box from VB

Posted on 2004-08-27
9
1,060 Views
Last Modified: 2008-01-09
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
   
0
Comment
Question by:SpringSnowman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 2

Expert Comment

by:craigewens
ID: 11910849
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
 
LVL 7

Expert Comment

by:_agj_
ID: 11910856
a textbox in a doc would be accessible as:

oDoc.TextBox1 etc.

say u can set

oDoc.TextBox1.Text = "1"
0
 
LVL 7

Expert Comment

by:_agj_
ID: 11910869
oDoc.InlineShapes("TextBox1").Text  = "1" should work
0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 

Author Comment

by:SpringSnowman
ID: 11910913
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
 
LVL 18

Accepted Solution

by:
JR2003 earned 500 total points
ID: 11911193
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
 

Author Comment

by:SpringSnowman
ID: 11911232
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
 
LVL 18

Expert Comment

by:JR2003
ID: 11911257
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
 
LVL 18

Expert Comment

by:JR2003
ID: 11911276
Just call the ReplaceText function, that calles the ReplaceTextInRange function

To call it
e.g.:

    ReplaceText "%AMNT%",lblValue.Caption
0
 

Author Comment

by:SpringSnowman
ID: 11911380
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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question