Solved

Find text inside a Word document Text Box from VB

Posted on 2004-08-27
9
1,055 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
  • 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
 

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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

758 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now