Solved

Find text inside a Word document Text Box from VB

Posted on 2004-08-27
9
1,058 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
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 

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

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Input past end of file vbs script 9 92
consolidate or create a new vba code for performing tasks 5 66
VBA error replacing data 6 39
How to make an ADE file by code? 11 83
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
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…
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…

770 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