Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    Visual Basic




Open A MS-Word Template And Replace Some Text


I got some code of how to open MS word within VB6, that's ok, but my question is, once I had that doc or template which is what i want ( a template), open, what do I have to do to update the template with the info. retreived from a data-base?........




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Open Word File And Replace Text.
Hey guys,

I'm trying to work out the code which will form the basis of a document generation function within excel. The aim is to use VBA to open a word file (which acts as a template) and replace certain strings (e.g. "[customer_name]") and replace them with pieces of data (in this case a particular customer's name). I've had a look arround on the net to see if anyone's mentioned this before but to no avail.

The code below is what I'm working with at the moment.


Code:
Private Sub CommandButton2_Click()
Dim LWordDoc As String
Dim oApp As Object

'Path to the word document
LWordDoc = "c:Doc1.doc"

If Dir(LWordDoc) = "" Then
MsgBox "Document not found."

Else
'Create an instance of MS Word
Set oApp = CreateObject(Class:="Word.Application")
oApp.Visible = True

'Open the Document
oApp.Documents.Open Filename:=LWordDoc

With oApp.Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "toreplace"
.Replacement.Text = "replaced"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
End If
Set oApp = Nothing
End Sub
The code is most likely totally knacked now from all of the random things I've tried to get the code to funtion as I'd like so it is probably totally flawed.

To clarify, I'd like to be able to do the following via VBA...
1) Open a particular word document.
2) Replace all instances of various strings with data from fields in the excel spreadsheet.
3) Give the user the option to save(under another filename) and/or print this document.

I shouldn't have any problems with stage 3 and the latter part of stage 2, its just a case of getting the simple "open the file and replace the strings" functionality up and running in the first place.

Thanks in advance for any help.

Regards,
Matt

Open Word Template
Is there a way to open a word template, make some changes...search and replace changes and then prompt the user to save the template as some other document?

How To Open Word Template?
I need to open a word template when a user hits the button. Then i need to add info to the document and save it as a different name.

Not sure how to specifically open a template.

Open A Document Word From A Template Of Word
Hello, I'm working in Visual Basic 6 and I want open a document word. But this document must be from a template of word (its name is Informe).

I do it with the code
Dim objWord As Word.Application
Dim objDoc As Word.Document

Set objWord = New Word.Application
Set objDoc = objWord.Documents.Add("C:Informe.dot")

It's ok but I only see the document, I want to see the menus of word,....
If it isn't possible can you send me the code to print this document?


Thank's and sorry for my poor english

How Can You Open A Text File, And Replace "WORD" With A String?
anyone know how to do this?

(and save it back )

How To Open A Specific Word Template.
Hi, I'm trying to cut my programming teeth on a little side project at work.

Situation: I want to be able to call up a specific MS Word template from within an Access database. I modified some code that I found on this site and can at least get Word to open a blank document marked "read only" but not the specific document I want.

Here is the code so far:

Private Sub OpenWord()
Dim WordApp As Word.Application
Dim WordTemp As Word.Template
Dim STRTempName As String
STRTempName = "\fltntshr001ITG_CommonIT ServiceeFDNDealer AlertsDealer System Alert.dot"
Set WordApp = New Word.Application
Set WordTemp = WordApp.Documents.Open(STRTempName)
WordApp.Visible = True
End Sub

Thank you to the original author and thanks greatly for any help in advance to you all.

Open MS Word Document/template Through VB6
Hi all, I am writing the following code to open a word template

Code:Dim objWord As Word.Application


Set objWord = New Word.Application
objWord.Visible = True
objWord.Documents.Open App.Path & "WordDotFile.dot", , , True, , "password"

The word template is password protected. This code does open the template file from VB6 but code macros of the template does not run. While I try to run the template directly, a vba form opens in the start up but when I open it through VB6 it does not evokes the form. Any guidance please...

Help - Need To Open And Read A Word Template From VB
Hi !!!

I have a Word Template file ( *.dot). which will have a text box and check box taking user input. i have to open that *.dot file and read the values given in the text box and check box and insert the values in to the db.how should i do it from VB.please help me in solving this problem.

Open A Word Template Save And Close
Hello,

I have some problem here figuring this out, , the plan is to open a template word file, write some data, SaveAs with new filename then close it. this code has some problem with it.



Set wdQE = New Word.Application
If UCase(cbxReportTemplate.Text) = "RIFFA" Then
wdQE.Documents.add (App.Path & " emplatesEnquiryRiffa.dot")
Else
wdQE.Documents.add (App.Path & " emplatesenquiry.dot")
End If

Call create_QEDoc(flvwsuppliers.TextMatrix(flvwsuppliers.Row, 1), flvwsuppliers.Row)


Dim oDoc As Document

Set oDoc = wdQE
oDoc.SaveAs "C:ProcEmailAttach" & txtRFname & ".doc"
oDoc.Saved = True
oDoc.Close


thanks in advance...

Open Word Template, Create New Document
How do i open a word template and create a new document from it?

There's like 20 parameters when opening a word.application
.documents.open(,,,,,,...... Mark P.
www.cafecartel.com
Providing Low Cost Powerful Point of Sale Solutions.

Global Text Replace In Multiple Word Replace
Hi All,
Sometime back, I stumbled upon a VB code (shown below), for performing word replace in multiple word files placed in a folder (global replacement). However, it has one disadvantage that this does not make the changes if the text appears in a "Text Box" or "Auto Shape". Please can some one help me modify the code so that the replacements are affected in these "Text Box and "Auto Shapes" also.

VB Code:
Private Declare Function GetFileAttributes Lib "Kernel32" Alias "GetFileAttributesA" (ByVal strPath As String) As Long Function ExistFileDir(sSpec As String) As BooleanDim af As Long    af = GetFileAttributes(sSpec)    ExistFileDir = (af <> -1)End Function Sub GetPathAndMask(ByRef Path As String, ByRef Mask As String)Dim x As Integer 'loop counterDim bExists As Boolean     For x = Len(Path) To 1 Step -1        If (Mid$(Path, x, 1) = "") Or _            (Mid$(Path, x, 1) = "/") Then            Mask = Mid$(Path, x + 1, Len(Path) - x)            Path = Left$(Path, x)            bExists = ExistFileDir(Path)            If (bExists = False) Then                Path = ""            End If            Exit Sub        End If    Next xEnd Sub  Function GetSubdirs(directory_text As String, dir_array() As String, counter As Integer) As Integer      Dim temp_var As String       On Error Resume Next       temp_var = Dir(directory_text, vbDirectory)        localcounter = 0       Do Until temp_var = ""           If temp_var <> "" Then              If GetAttr(directory_text & temp_var) And vbDirectory And Mid$(temp_var, 1, 1) <> "." Then                   ReDim Preserve dir_array(counter)                   dir_array(counter) = directory_text & temp_var & ""                   counter = counter + 1                localcounter = localcounter + 1           End If        End If           temp_var = Dir()    Loop        Dim x As Integer 'loop counter    Dim CurDir As String    For x = 1 To localcounter Step 1        CurDir = dir_array(x - 1 + counter - localcounter)         counter = GetSubdirs(CurDir, dir_array, counter)    Next x     GetSubdirs = counterEnd Function Private Sub CloseBtn_Click()    Unload QueryFormEnd Sub Private Sub FindBtn_Click()   ' just find, no replace   Call DoReplace(wdReplaceNone)End Sub Private Sub ReplaceBtn_Click()   ' replace it   Call DoReplace(wdReplaceAll)End Sub Private Sub DoReplace(ReplaceMode As Long)        Dim FilePath As String    Dim Mask As String    Dim LogFile As String    Dim ChangeCount As Integer        If (Search_Box.Text = "") Then        MsgBox "Please enter a Search String"        Exit Sub    End If     FilePath = FileMask_Box.Text    GetPathAndMask FilePath, Mask    If ((FilePath = "") Or (Mask = "")) Then                                                Call MsgBox("Invalid Path! Please enter a valid file path!  ", vbOKOnly + vbCritical + vbApplicationModal + vbDefaultButton1, "Invalid Input")                                Exit Sub    End If     LogFile = FilePath & "Cleanser_Results.txt"     ChangeCount = ReplaceInDir(LogFile, FilePath, Mask, ReplaceMode)    If (Search_Subdir.Value = True) Then        Dim dir_array() As String        Dim NumDirs As Integer        NumDirs = GetSubdirs(FilePath, dir_array, 0)        Dim x As Integer 'loop counter        Dim CurDir As String        SubCount = 0        For x = 1 To NumDirs Step 1            CurDir = dir_array(x - 1)            SubCount = SubCount + ReplaceInDir(LogFile, CurDir, Mask, ReplaceMode)        Next x    End If        If ReplaceMode = wdReplaceNone Then        MsgBox (ChangeCount + SubCount) & " file(s) found"    Else        MsgBox (ChangeCount + SubCount) & " file(s) changed"    End If End Sub Function ReplaceInDir(LogFile As String, Path As String, Mask As String, ReplaceMode As Long) As IntegerDim ChangedCount As IntegerDim FileName As StringDim aStory As RangeDim FindCount As Long     ChangedCount = 0    FindCount = 0    FileName = Dir(Path & Mask)        Do Until FileName = ""        DoEvents        On Error GoTo CantOpenFile        Documents.Open FileName:=Path & FileName                If Process_Field_Codes.Value = True Then            ActiveWindow.View.ShowFieldCodes = True        End If         On Error GoTo 0        On Error GoTo CantChangeTracking        On Error GoTo 0        ActiveDocument.Saved = True 'don't count ShowRevisions        ' Can't change protected documents        If ActiveDocument.ProtectionType <> wdNoProtection Then            ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges            GoTo DocumentProtected        End If         For Each aStory In ActiveDocument.StoryRanges        aStory.Find.Execute _            FindText:=Search_Box.Text, _            ReplaceWith:=Replace_Box.Text, _            MatchCase:=Match_Case.Value, _            MatchWildcards:=Reg_Exp.Value, _            MatchWholeWord:=Whole_Word.Value, _            Replace:=ReplaceMode                        If aStory.Find.Found Then FindCount = FindCount + 1        Next aStory                'Repeat the process after toggling Field Codes        If Process_Field_Codes.Value = True Then            ActiveWindow.View.ShowFieldCodes = Not ActiveWindow.View.ShowFieldCodes                For Each aStory In ActiveDocument.StoryRanges                    aStory.Find.Execute _                    FindText:=Search_Box.Text, _                    ReplaceWith:=Replace_Box.Text, _                    MatchCase:=Match_Case.Value, _                    MatchWildcards:=Reg_Exp.Value, _                    MatchWholeWord:=Whole_Word.Value, _                    Replace:=ReplaceMode                    If aStory.Find.Found Then FindCount = FindCount + 1                    Next aStory        End If                If Not ActiveDocument.Saved Then 'then we must have changed it            Open LogFile For Append As #1            Print #1, Date & " " & Time & " Changed " & Chr$(34) & Search_Box.Text & Chr$(34) & " to " & Chr$(34) & Replace_Box.Text & Chr$(34) & " in " & Path & FileName            Close #1            On Error GoTo CantSaveFile            ActiveDocument.Save            ChangedCount = ChangedCount + 1        Else            ' print a log even if found something            If (ReplaceMode = wdReplaceNone) And FindCount > 0 Then               Open LogFile For Append As #1               Print #1, Date & " " & Time & " Found " & Chr$(34) & Search_Box.Text & Chr$(34) & " in " & Path & FileName               Close #1               On Error GoTo CantSaveFile               ChangedCount = ChangedCount + 1            End If        End If        FindCount = 0                ActiveDocument.Close SaveChanges:=wdDoNotSaveChangesNextFile:        FileName = Dir    Loop       ReplaceInDir = ChangedCount    Close    On Error GoTo 0        GoTo AllDone    CantChangeTracking:    Open LogFile For Append As #1    Print #1, Date & " " & Time & " Could not modify Tracking status on " & Path & FileName    Close #1    Resume NextCantSaveFile:    Open LogFile For Append As #1    Print #1, Date & " " & Time & " Could not save " & Path & FileName    Close #1    Resume NextCantOpenFile:    Open LogFile For Append As #1    Print #1, Date & " " & Time & " Could not open " & Path & FileName    Close #1    Resume NextFile DocumentProtected:    Open LogFile For Append As #1    Print #1, Date & " " & Time & " Could not process protected document " & Path & FileName    Close #1    GoTo NextFile AllDone:End Function


Thanks in advance,
Lonely

Inserting Text Into Word Template With Bookmarks
I just started using the word functions yesterday, so I'm still pretty clueless about how to put this together. What I have is a form that a user can enter some data into, and then check that form off as ready to print. In the future they will be able to batch print all the forms that are checked, but at this point I'm just trying to do one.
I created a template in Word and inserted bookmarks where I wanted the form data to be filled in. This is the code I have right now:


Code:
Dim objWord As Word.Application
Dim aDoc As Word.Document
Dim var As Variant

Set objWord = New Word.Application

Set aDoc = Documents.Add("c:Renewal Template.dot")
aDoc.Activate

'Contact
ActiveDocument.Bookmarks("contact").Select
Selection.InsertAfter (newRepForm.Text20(57) & " " & newRepForm.Text20(58))

'Branch Number
ActiveDocument.Bookmarks("branchNum").Select
Selection.InsertAfter (newRepForm.Text20(65))

'This goes on for about 16 more bookMarks
'Then I have this next line, though it doesn't work

ActiveDocument.PrintPreview
msgbox "Done Printing"
And that's it. It makes it through the code and displays the message box, but nothing else seems to happen.
What am I missing? I searched these forums yesterday enough to decide bookmarks were the way to go, but like I said I've never used and of the word functions and I feel like I'm missing something fundamental. Any help would be appreciated.

Kevin

Help With Importing Text From VB Forms To A Word Template
Hi,

I am new to VB and fighting with deadlines on this project. Running (VB6.0 with Office 2000) . My goal is to import the selected data from two VB forms (data in the form of text boxes, combolist and listbox) to a word template. The text should be inserted at the bookmarks in the word template and a part of it in a table.

Set mWord = New Word.Application
Call mWord.Documents.Add
mWord.Documents.Add ("C:MicrosoftTemplatesManual.Dot")
ActiveDocument.Bookmarks("Bmk1").Select

I guess,... with this code,.. I might be able to load the template and insert the cursor at the bookmark (Bmk1). Please guide me if I am right with this and how can I insert the text at the location.

Any reference articles will be greatly appreciated,
Thanks,
SK

Blocking Template After Exporting From Access 2002 To A Word Template
I am having some difficulty determining the appropriate code for stopping a template from popping up after I close the document to which my Access data has been transferred to. My VB code automatically saves the document, but when I quit Word, my original template pops up. Whatever code I insert into VBE doesn't seem to stop it. I hope someone can help me.... Here's the relevant portion of the code below:

'Creates a Word instance to use for the 8D form. Uses the existing
'Word instance if there is one; otherwise, creates a new instance.
Set objWord = GetObject(, "Word.Application")
If Err.Number = 429 Then
'Word isn't running; creating a Word object.
Set objWord = CreateObject("Word.Application")
Err.Clear
End If

On Error GoTo Command126_ClickError

strDocsPath = "V:QCProblem Cases" & ""
strSaveName = "BWA CAR No. " & Me![Customer Tracking Number] & ".doc"
strSaveNamePath = strDocsPath & strSaveName
strTemplatePath = "V:QCProblem Cases" & ""
strWordTemplate = strTemplatePath & "8Dform.dot"

'Check for existence of template in template folder,
'and exit if not found
strTestFile = Nz(Dir(strWordTemplate))
If strTestFile = "" Then
MsgBox strWordTemplate & " template not found; can't create 8D form"
Exit Sub
End If

Set objDocs = objWord.Documents
objDocs.Add strWordTemplate
.
.( I have removed the section which relates fields between Access and the template...there's nothing that controls opening and closing of the document)
.
.
With objWord
.Visible = True
.Selection.WholeStory
.Selection.Fields.Update
Debug.Print "Going to save as " & strSaveName
.ActiveDocument.SaveAs strSaveName
.Activate
.Selection.EndKey Unit:=wdStory
End With

Command126_ClickExit:
Exit Sub

Command126_ClickError:
MsgBox "Error No: " & Err.Number & "; Description: " & Err.Description
Resume Command126_ClickExit

End Sub

I would appreciate if I receive a reply ASAP (job-related!!)

Unhide Hidden Text By Macro In Word-97 (secured Template ).
In a template hidden text is used. Before this text I inserted a checkbox.
I would like to unhide the hidden text when I click on the checkbox.
I made a macro which unhides the hidden text.
When I change the properties of the checkbox with the command to run the defined macro it doesn't react.
Of course I secured the section otherwise my form doesn't work.

Since the upperside method doesn't work properly I tried to insert the text from a separate document.
I also tried this by using a checkbox in the main document.
Again I defined a macro which inserts the text and places it below the checkbox.
Unfortunately this doesn't function either.

Is there someone who has a idea for solving this problem.

How To Paste On A Word Template Without Loosing The Formatting Of The Template?
I'm new on VB please help me!
I have to fill some special word template with informations caming from an access DB.
Here the code I'm using now.

Private Sub SearchAndReplaceOnce(monDocWord As Word.Document, strTagARemplacer As String)

Dim maPlage As Variant
Set maPlage = monDocWord.Content

With maPlage.Find
.ClearFormatting
.Execute FindText:=strTagARemplacer
If .found = True Then maPlage.Paste
End With
End Sub

All this code is working but the method Paste is replacing also the formatting that I have pre-defined on the word template.
How can I do to avoid this problem?
Thanks

Word Object To Save Template As A Template.
I use a word object to open a template and resave it to template.
The reason I'm opening the template is that I want to run a macro that fills the template with data from bookmarks.

I use this code:

Code:
Dim objWordApp As Object
Set objWordApp = CreateObject("Word.Application")
objWordApp.Documents.Add Template:=TemplatePath, NewTemplate:=True
objWordApp.ActiveDocument.LoadMe sConn, FunctionId, sFunctionType, SupplierId
objWordApp.ActiveDocument.SaveAs FileName:=WorkPath & FileName
objWordApp.ActiveDocument.Close SaveChanges:=wdSaveChanges

But when opening the new template I get this annoying reference to the old template. The old macros doesn't save in the new template.

When running save as in word on a template the macros are transferred to the new file without referencing to the old macro.

How do you do this in VB?

Replace Text In Word Doc Using VB6
Hi, i'm a problem when i try to replace test in MSword in VB6.
'
Public Function CreaDoc() As Boolean
Dim mDoc As New Word.Application

mDoc.Documents.Add (mvarModelloDoc)
mDoc.Documents(1).Activate
mDoc.Documents(1).SaveAs (mvarCartella & mvarNomeDocumento)
If mDoc.ActiveDocument.ProtectionType <> wdNoProtection Then
mDoc.ActiveDocument.Unprotect
End If

With mDoc.ActiveDocument.Content.Find
.Forward = True
.Execute FindText:="@DATA@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=DATA, Replace:=wdReplaceAll .Execute FindText:="@PROTO@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=Protocollo, Replace:=wdReplaceAll
.Execute FindText:="@RAGSOC@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=RagSoc, Replace:=wdReplaceAll
.Execute FindText:="@INDIRIZZO@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=Indirizzo, Replace:=wdReplaceAll
.Execute FindText:="@CAP@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=Cap, Replace:=wdReplaceAll
.Execute FindText:="@CITTA@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=Citta, Replace:=wdReplaceAll
.Execute FindText:="@PROV@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=Provincia, Replace:=wdReplaceAll
.Execute FindText:="@OGGETTO@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=OggettoPratica & " - " & Oggetto, Replace:=wdReplaceAll
.Execute FindText:="@CORPOTESTO@", MatchWholeWord:=True, Wrap:=wdFindContinue, ReplaceWith:=CorpoTesto, Replace:=wdReplaceAll
End With
mDoc.Documents.Save
mDoc.Documents.Close

end function
'
In the line marked in BOLD, this error occur:
"Run-time error '-2147220995 (800401fd)':

Automation error
Object is not connected to server"

i use These reference
"Microsof Office 9.0 Object Library"
"Microsof Word 9.0 Object Library"

Please, help me!!!!

PTM

Replace Text In Word Doc
I use this code blow to edit a text formated file and it works
but when i try it on a MS word doc, it fails.
Does it have to do with the fact that word docs
are in a rich text format, and how can i get around
this problem?

Dim Path As String, f As Integer, temp As String
Path = "c: arget.txt" ' text files works , Word files don't
f = FreeFile
Open Path For Binary As #f
temp = Space(LOF(f)) 'Create a buffer for the file
Get #f, , temp 'Load the textfile into the buffer
temp = Replace(temp, "<", "&lt;") 'replace < with &lt;
temp = Replace(temp, ">", "&gt;") 'replace < with &lt;
Close #f 'close the file and kill it.
Kill Path 'This because the previous data is longer then this data
Open Path For Binary As #f
Put #f, , temp 'Write the data into the file and close it once again
Close #f
End Sub

Replace Text In A Table In Word
Hello,

I'm using a word template in which i want to replace a certain word at a certain position for a newly created table.
How can i do this.

I have used this part of the code to find:

With objWord.ActiveDocument.Content.Find
.Text = table"
With .Replacement
.ClearFormatting
End With
.Execute Format:=True, Replace:=wdReplaceAll
End With

This does nothing then finding the word "table" but i want to create a selection or range so the i can replace this word for a table with for example 3 rows en 3 colums.

Can anyone help me out?

Kind regards,

Maruq

Need To Replace A Word With Another In A Text File
Hi,
I am using the following code to write to text file which is already existing

Open log_fname For Append As #1

Print #1, " Header "
Print #1, "hi"

Close #1

I need to search for header and replace "hi" with "hello".

how can i replace a word under a particular header?

expecting a fast response
thanks in advance

Need Help To Open File Replace Text And Save/close
I need to open a file like a c:ob.txt replace all "dog" with "cat" and save and close the file.

Word 2000: Replace Text In A String
Hello!

I am not at all familiar with VB integration to Word or VB at all for that matter..

If someone could answer me on my question it would help me a great deal!!

Here is the thing:
I have several documents in a folder. Some of these documents are based on a template that is located on a server that no longer exists. Because of this - the documents takes 30 seconds to load. And since this doesn't happen to all of the documents in the folder it is a bit stressful to go through all of the documents.

This is what I want to do:
Search through the Attached template for the word "server1" and replace this with "server2".

I tried doing this with the Record Macro function in Word and this is what I got:

Sub test()
'
' test Macro
' Macro recorded 28.05.2003 by me
'
ChangeFileOpenDirectory "C:officetestold"
Documents.Open FileName:="""Steffensen hotelregning purring 3.12.98.doc""" _
, ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
wdOpenFormatAuto
With ActiveDocument
.UpdateStylesOnOpen = False
.AttachedTemplate = _
"\server2Templatesdefault_template.dot"
End With
End Sub


Well, it changes the template, but I want it to search for the word server1 and replace it with server2 IF server1 exists.

I already have the code to go through all the documents in a folder - I only need the search part...

Is this at all possible? I will be for ever grateful to the one who can help me :-)

***Resolved*** How To Replace Text Between Bookmarks In Word
Does anyone know how to replace text between two bookmarks in Word 2000? What I need to do is replace whatever text is between the bookmarks with a predefined phrase.

The actual text between the bookmarks to be replaced will be different everytime this routine is run so I can't use find and replace.

Thanks for your input.

Find/replace Text In Word Document From Vb?
Hi,

I need to be able to automate a find/replace function from within VB for a specific Word document.

For example, I have a document named Document1.doc. There is text in it as follows:

Hi, my name is <NAME>!

From within VB, I want to be able to replace the <NAME> with "Dan".

The values would not come from a database, it will be hard coded, so no need to show any data connectivity code. Just a plain and simple find/replace function.

Any help would be appreciated..

Dan

Word: How To Replace Text In A Table In A Header
Hi,

In a Word document exists a table in a header. How can I select text in a cell of this table and replace it with something else?

Thanks for your help!



Edited by - ELOOP on 2/17/2006 6:22:38 AM

żIs There Any Way To Search And Replace Inside Word´s Text Boxes?
Hi there, many regards to everyone. This is my first post after being an asidous reader. Great work in this site.

After reading all the search and replace related items in the forums, I haven´t found an answer for my little problem.

I´ve made a VB code in order to search and replace inside a document but I´ve got a problem. This routine does not "look inside" Ms Word´s Textboxes, just replaces text in a document that is outside the TextBoxes (and of course, heading and footer of document). Here is the code


Private Sub CommandButton1_Click()

Set Myrange = ActiveDocument.Range(Start:=0, End:=Selection.End)

Selection.Find.Execute findtext:="searchitem1", replacewith:=TextBox1.Text, Replace:=wdReplaceAll
.
.
.

Selection.Find.Execute findtext:="searchitemN", replacewith:=TextBoxN.Text, Replace:=wdReplaceAll

MsgBox ("Replacement finished")

End Sub

Any hints on this question ?

Thanks in advance

Global Text Find And Replace In Word Files
Hi All,
Sometime back, I stumbled upon a VB code (shown below), for performing word replace in multiple word files placed in a folder (global replacement). However, it has one disadvantage that this does not make the changes if the text appears in a "Text Box" or "Auto Shape". Please can some one help me modify the code so that the replacements are affected in these "Text Box and "Auto Shapes" also.
-------------------start code---------
Private Declare Function GetFileAttributes Lib "Kernel32" Alias "GetFileAttributesA" (ByVal strPath As String) As Long

Function ExistFileDir(sSpec As String) As Boolean
Dim af As Long
af = GetFileAttributes(sSpec)
ExistFileDir = (af <> -1)
End Function

Sub GetPathAndMask(ByRef Path As String, ByRef Mask As String)
Dim x As Integer 'loop counter
Dim bExists As Boolean

For x = Len(Path) To 1 Step -1
If (Mid$(Path, x, 1) = "") Or _
(Mid$(Path, x, 1) = "/") Then
Mask = Mid$(Path, x + 1, Len(Path) - x)
Path = Left$(Path, x)
bExists = ExistFileDir(Path)
If (bExists = False) Then
Path = ""
End If
Exit Sub
End If
Next x
End Sub


Function GetSubdirs(directory_text As String, dir_array() As String, counter As Integer) As Integer

Dim temp_var As String


On Error Resume Next


temp_var = Dir(directory_text, vbDirectory)


localcounter = 0

Do Until temp_var = ""

If temp_var <> "" Then

If GetAttr(directory_text & temp_var) And vbDirectory And Mid$(temp_var, 1, 1) <> "." Then

ReDim Preserve dir_array(counter)

dir_array(counter) = directory_text & temp_var & ""

counter = counter + 1
localcounter = localcounter + 1
End If
End If

temp_var = Dir()
Loop

Dim x As Integer 'loop counter
Dim CurDir As String
For x = 1 To localcounter Step 1
CurDir = dir_array(x - 1 + counter - localcounter)
counter = GetSubdirs(CurDir, dir_array, counter)
Next x

GetSubdirs = counter
End Function

Private Sub CloseBtn_Click()
Unload QueryForm
End Sub

Private Sub FindBtn_Click()
' just find, no replace
Call DoReplace(wdReplaceNone)
End Sub

Private Sub ReplaceBtn_Click()
' replace it
Call DoReplace(wdReplaceAll)
End Sub

Private Sub DoReplace(ReplaceMode As Long)

Dim FilePath As String
Dim Mask As String
Dim LogFile As String
Dim ChangeCount As Integer

If (Search_Box.Text = "") Then
MsgBox "Please enter a Search String"
Exit Sub
End If

FilePath = FileMask_Box.Text
GetPathAndMask FilePath, Mask
If ((FilePath = "") Or (Mask = "")) Then





Call MsgBox("Invalid Path! Please enter a valid file path! ", vbOKOnly + vbCritical + vbApplicationModal + vbDefaultButton1, "Invalid Input")



Exit Sub
End If

LogFile = FilePath & "Cleanser_Results.txt"

ChangeCount = ReplaceInDir(LogFile, FilePath, Mask, ReplaceMode)
If (Search_Subdir.Value = True) Then
Dim dir_array() As String
Dim NumDirs As Integer
NumDirs = GetSubdirs(FilePath, dir_array, 0)
Dim x As Integer 'loop counter
Dim CurDir As String
SubCount = 0
For x = 1 To NumDirs Step 1
CurDir = dir_array(x - 1)
SubCount = SubCount + ReplaceInDir(LogFile, CurDir, Mask, ReplaceMode)
Next x
End If

If ReplaceMode = wdReplaceNone Then
MsgBox (ChangeCount + SubCount) & " file(s) found"
Else
MsgBox (ChangeCount + SubCount) & " file(s) changed"
End If

End Sub

Function ReplaceInDir(LogFile As String, Path As String, Mask As String, ReplaceMode As Long) As Integer
Dim ChangedCount As Integer
Dim FileName As String
Dim aStory As Range
Dim FindCount As Long

ChangedCount = 0
FindCount = 0
FileName = Dir(Path & Mask)

Do Until FileName = ""
DoEvents
On Error GoTo CantOpenFile
Documents.Open FileName:=Path & FileName

If Process_Field_Codes.Value = True Then
ActiveWindow.View.ShowFieldCodes = True
End If

On Error GoTo 0
On Error GoTo CantChangeTracking
On Error GoTo 0
ActiveDocument.Saved = True 'don't count ShowRevisions
' Can't change protected documents
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
GoTo DocumentProtected
End If

For Each aStory In ActiveDocument.StoryRanges
aStory.Find.Execute _
FindText:=Search_Box.Text, _
ReplaceWith:=Replace_Box.Text, _
MatchCase:=Match_Case.Value, _
MatchWildcards:=Reg_Exp.Value, _
MatchWholeWord:=Whole_Word.Value, _
Replace:=ReplaceMode

If aStory.Find.Found Then FindCount = FindCount + 1
Next aStory

'Repeat the process after toggling Field Codes
If Process_Field_Codes.Value = True Then
ActiveWindow.View.ShowFieldCodes = Not ActiveWindow.View.ShowFieldCodes
For Each aStory In ActiveDocument.StoryRanges
aStory.Find.Execute _
FindText:=Search_Box.Text, _
ReplaceWith:=Replace_Box.Text, _
MatchCase:=Match_Case.Value, _
MatchWildcards:=Reg_Exp.Value, _
MatchWholeWord:=Whole_Word.Value, _
Replace:=ReplaceMode
If aStory.Find.Found Then FindCount = FindCount + 1
Next aStory
End If

If Not ActiveDocument.Saved Then 'then we must have changed it
Open LogFile For Append As #1
Print #1, Date & " " & Time & " Changed " & Chr$(34) & Search_Box.Text & Chr$(34) & " to " & Chr$(34) & Replace_Box.Text & Chr$(34) & " in " & Path & FileName
Close #1
On Error GoTo CantSaveFile
ActiveDocument.Save
ChangedCount = ChangedCount + 1
Else
' print a log even if found something
If (ReplaceMode = wdReplaceNone) And FindCount > 0 Then
Open LogFile For Append As #1
Print #1, Date & " " & Time & " Found " & Chr$(34) & Search_Box.Text & Chr$(34) & " in " & Path & FileName
Close #1
On Error GoTo CantSaveFile
ChangedCount = ChangedCount + 1
End If
End If
FindCount = 0

ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
NextFile:
FileName = Dir
Loop

ReplaceInDir = ChangedCount
Close
On Error GoTo 0

GoTo AllDone

CantChangeTracking:
Open LogFile For Append As #1
Print #1, Date & " " & Time & " Could not modify Tracking status on " & Path & FileName
Close #1
Resume Next
CantSaveFile:
Open LogFile For Append As #1
Print #1, Date & " " & Time & " Could not save " & Path & FileName
Close #1
Resume Next
CantOpenFile:
Open LogFile For Append As #1
Print #1, Date & " " & Time & " Could not open " & Path & FileName
Close #1
Resume NextFile

DocumentProtected:
Open LogFile For Append As #1
Print #1, Date & " " & Time & " Could not process protected document " & Path & FileName
Close #1
GoTo NextFile

AllDone:
End Function
--------------------end code-------------

Thanks in advance,
Lonely

żIs There Any Way To Search And Replace Inside Word´s Text Boxes?
Edit by Moderator: Please do not respond to threads over 1 month old as per our Posting Guidelines. By all means refer to an existing thread in your own post as I have doen for you this time. Thanks
Re: http://www.xtremevbtalk.com/showthread.php?t=84908

I'm pretty sure this is exactly what i'm looking for Sergio.
But i am having trouble with: Dim aSHAPES As Shape
keep getting the error: Type 'Shape' is not defined.

Am I missing somthing? I really appreciate your help.

How Can I Replace Text In The Footer Of A Word Document? (Resolved)
Environment:
VB6 (SP6)
Word v9 (Word 2000) or later
 

My VB app creates a Word document from a Word template (.dot file)

The template contains special text fields that I replace with content from within my app after the document is created.

This works fine but now I want to be able to replace a field that is in the footer.
(I need a reference number to appear on every page)
The method I’m using only seems to work for the body of the document.
If I put a special field in the footer it’s ignored.

Here is an extract from the dot file:

==========start================

[contactName]

[distributorAddress]

Quotation No. Q Quote:

[date]

[description]


Dear [contactFirstName],

==========end===============

And here’s the procedure I use to replace text.
(MDImain.WordApp is a reference to the document)

Code:Private Sub replaceKeyword(keyword As String, value As String)
    ' Replace a keyword in the template with the new content
    ' This is done using the Search and Replace functionality of Word
 
    MDImain.WordApp.Selection.HomeKey unit:=wdLine
    With MDImain.WordApp.Selection.Find
        .Text = "[" & keyword & "]"
        .Replacement.Text = value
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
End Sub
Here’s an example of using the procedure.

Code: ' Distributor address
        fieldValue = ""
        fieldValue = fieldValue & rsDistributor!name & vbCr
        fieldValue = fieldValue & rsDistributor!Address1 & vbCr
        If rsDistributor!Address2 <> "" Then
            fieldValue = fieldValue & rsDistributor!Address2 & vbCr
            If rsDistributor!Address3 <> "" Then
                fieldValue = fieldValue & rsDistributor!Address3 & vbCr
            End If
        End If
        If rsDistributor!postCode <> "" Then
            fieldValue = fieldValue & rsDistributor!postCode & vbCr
        End If
        replaceKeyword "distributorAddress", fieldValue
        
        replaceKeyword "quote", Format(rsQuote!quoteID) & rsRevision!revID
        replaceKeyword "date", FormatDateTime(rsRevision!QDate, vbLongDate)

So, my question is, how can I replace text in a footer?

Cheers,

Mac

Edited by - Mac2309 on 1/5/2005 6:42:09 AM

Replace Word Text With Access Memo Field
I am trying to modify a Word document by finding text and then replacing it with information stored in Access data fields. Some of these fields are of type Memo. The way that works well with fields of type Text is:

Code:Set myRange = WordDoc.Content
myRange.Find.Execute FindText:="**TextField**", ReplaceWith:=TextField

In this case "**TextField**" is the text in the Word document that will be replaced by the data from the access field called "TextField". This works very well. However, when I try to use a field of type Memo, I get an error "Type Mismatch". Is there an easy way to get around this or alternate method??

Currently I am using a brute force method that breaks the Memo text into multiple, smaller strings, similar to the following:

Code:mylines() = Split(MemoField)
search = "**MemoField**"

For I = 0 To UBound(mylines)
   ' check for last catenation
   If UBound(mylines) = I Then
      search = ""
   End If
   Set myRange = WordDoc.Content
   If Not InStr(mylines(I), Chr(10)) = 0 Then
      mylines(I) = Replace(mylines(I), Chr(10), "")
   End If
   ' if the string is not a line feed
   If Not mylines(I) = Chr(10) Then
      ' replace with string, add search text for next string.
      myRange.Find.Execute FindText:="**MemoField**", ReplaceWith:=mylines(I) & " " & search
   End If
Next I


As you can see this brute force method is ugly and takes a lot of extra code. But the worst part is performance. The best way to break up the memo is by using the white space as the delimeter. This creates a rather large number of strings (hundreds) and it takes some time to make the array of strings and then find and replace until the whole array is empty.

If anyone knows of a better, more efficient method I would truly be grateful!

Find Word Field Code, Replace With Normal Text
Please help!!

Before posting this thread, I have read the thread "Word FAQ - Word VBA 101" by Wamphyri:

http://www.xtremevbtalk.com/showthread.php?t=125085

It was very helpful, but still cannot solve my problem.

At the moment I am using VB6. I was able to find text, but was not able to find field code. Specifically, to find Spanish TIME field code of

TIME @ "d' de 'MMMM' de 'yyyy"

I tried:

objRange.Range.Find.Text = "{ TIME @ ""d' de 'MMMM' de 'yyyy"" }"

and also this:
objRange.Range.Find.Text = "{ TIME @ "d' de 'MMMM' de 'yyyy" }"

and this:
objRange.Range.Find.Text = "TIME @ "d' de 'MMMM' de 'yyyy""

but it does now work. Also, when I open my Word document as text in Notepad, it shows something like this:

TIME @ "d' de 'MMMM' de 'yyyy" 22 de noviembre de 2004

It seems that even if I find the field code, I will be have problem replacing the TIME field code, as there is an actual date trailing at the end. That actual date has to be replaced also. All these field codes will be replaced by looking up the file name in a database. I have no problem looking up the informatino in the database, but I can't do much if I cannot find the field code!

There are about 4000 files that have the field code. It's been bugging me for a long time now. Could Wamphyri, or another Word VBA guru out there help me out?? Thanks!!

wps

Access To Word: Closing And Opening Word Template
Hi there,
following Function is calling from Access and opens a Word-Template to replace the Bookmark with a Teststring. No Problem, but by a second Call, the Bookmark is not found cause the Worddocument is open in Background (although its closed with "objWord.Quit SaveChanges:=False"). IS there a better Way to close a Worddocument or did anybody find another mistake in that Code? I'm a Newie in VB/Word and I hope this is a clear Description of that Problem.

greetz & Thanks
Daniel


Code:
Public Function test() As Long
    Dim MyRange As Range
    Dim objWord As Word.Application
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = False
    objWord.DisplayAlerts = 0
  Dim oDoc As Word.Document
  Set oDoc = objWord.Documents.Open(getDbPath() & "Templates est.dot", ReadOnly:=True, ConfirmConversions:=False, AddToRecentFiles:=False)
  If ActiveDocument.Bookmarks.Exists("TEST") Then
    ActiveDocument.Bookmarks("TEST").Range.Text = "ABCDEFG"
    ActiveDocument.Bookmarks.Add Name:="TEST", Range:=Selection.Range
  End If
savEnv = objWord.Options.PrintBackground
objWord.Options.PrintBackground = False
oDoc.PrintOut
objWord.Options.PrintBackground = savEnv
objWord.Quit SaveChanges:=False
Set objWord = Nothing
test = 1
End Function

Open A Text File And Replace Parts Inside The File With Something Else??
how can i open app.path & " est.txt" and replace $Download with <a href="http://www.download.com">Download</a>

anyone know?

How To Paste Text In An Open Word Doc?
Hey all!
Got a question for yas.
I have a rich text box that opens a rtf file.
i also have an export button on my form that opens the file in word or if a selection is made it opens word and pastes the selected text into a new document.
but what i would like to know is if a document is already open, how do i go about adding the selected text where the cursor is located. any ideas?

thanks!
primal

this is my code so far....Code:Private Sub cmdExport_Click()
    Dim myWord As Object
    Dim myDocument As Object

    Set myWord = CreateObject("Word.Application")
    If RichTextBox1.SelLength = 0 Then
        myWord.Visible = True
        Set myDocument = myWord.Documents.Open(FileName:=FileList.Path & "" & FileList.FileName, ReadOnly:=False)
    Else
        ' code for exporting selection
        myWord.Visible = True
        Set myDocument = myWord.Documents.Add
        myWord.Selection.InsertAfter RichTextBox1.SelText
    End If

    Set myWord = Nothing
End Sub



Edited by - primal on 12/7/2003 7:54:05 PM

Open Word Doc And Export Just Plain Text
how can i open a word doc and just grab the text of the document? i want remove all the word formatting in file and have just plain old text.

any ideas?
GK

Open Word, Insert Text Then Run Macro
I use the following code to open MS Word and insert the contents of a Listbox. What I'm looking is that once the contents of the listlox are inserted can I run a macro that I have created in Word called 'AutomateReport'?

Code:
Private Sub CmdNext_Click()
Dim n As Integer
Dim TextToSave As String
Dim fNum As Integer
Dim FileName As String
Dim DocToOpen As String
Dim DocPath As String
Dim MyReport As Object

If LstSelected.ListCount <> 0 Then

DocPath = App.Path
DocToOpen = DocPath & "Template.doc"

For n = 0 To LstSelected.ListCount - 1
TextToSave = TextToSave & LstSelected.List(n)
'add delimiter, except on last item
If n < LstSelected.ListCount - 1 Then TextToSave = TextToSave & vbLf
Next n

Set MyReport = CreateObject("Word.Basic")
MyReport.FileOpen DocToOpen

With MyReport
.EditGoto "StartDocument"
.Insert TextToSave

End With
Dim objWord As Word.Application

Set objWord = New Word.Application
objWord.Visible = True
objWord.Documents.Open DocToOpen, , , True
Else
MsgBox "No items in list", vbCritical, "Warning"
End If

End Sub

Insert Text From VB 6 App Into Open MS Word Document
My wife handles medical dictation and stores some blocks of standard dictation in a text file.  I wrote a small VB app to make searching through the file easier, but she still has to paste the found text from the clipboard (copying to the clipboard from the app is done with one button) into the document.  Is there a way to have the VB app automatically insert text into an open Word document at the point the cursor is?

I searched the FAQs and the post history for something related to this, but didn't find anything that appeared to address this particular thing.

Lee

Enter Text Into Open Word File
Hi,

I have the following bit of code, that enters text into a blank word file when opened.

CODESet word_server = CreateObject("Word.Application")
    word_server.Caption = "My Document"
    word_server.documents.Add , , wdNewBlankDocument, True
    word_server.activedocument.PageSetup.Orientation = wdOrientLandscape
    word_server.activedocument.PageSetup.TopMargin = 72 '72 points = 1 inch.
    word_server.activedocument.PageSetup.BottomMargin = 72
    word_server.activedocument.PageSetup.LeftMargin = 36
    word_server.activedocument.PageSetup.RightMargin = 36
    word_server.activedocument.content.InsertParagraph
    word_server.activedocument.content.InsertParagraph
    word_server.activedocument.content.Paste 'If you have an image in clipboard
    word_server.activedocument.content.InsertParagraphAfter
    word_server.activedocument.content.insertafter " My Text Here "
    word_server.Visible = True

How To Open Word, Paste Text Into A New Doc BUT As HTML...
I'm using Word.Open and Documents.Add to open Word from my VB6 app and create a new document. I'm then pasting the contents of the clipboard in. This all works. So far, so unspectacular.

However, the text I'm pasting in from the clipboard is HTML. Since I'm only doing all this so I can use Word's spellchecker, I don't want to be checking HTML tags....

So, what I need is a way to force the new document created by Documents.Add to be a web page so that only the non-tag part of the HTML is spell checked.

Any ideas how to do this? And without Word adding all the surplus tags it normally does when creating a new web page from scratch.

Thanks in advance.

Open Template
Hi everyone,

I'm trying to open a new document based on a template that I created from VB6.
My template is in the 'User Templates' folder for MS Word.
The only way I was able to do that is by creating a dummy doc based on my template, opening that doc, then opening AttachedTemplate, closing dummy doc. This kind of works, but there's got to be a shorter way to open the template.

Thanks for your help.

Open Template In VB6
Hi

I have a template named BLANK.xlt and what i am hoping to do, is, when i run my app, i would like my template to appear on screen everytime the app is opened, but, at the moment I am struggling on how i can do this.

When the app, and template is opened, the user will (hopefully) be able to add items into the cells of my template and once finished, save the edited template as their new document.

Can anyone please give me advice on how i can achieve this

Many many thanks in advance

Open A Word Doc With Wordpad And Save As A Text File
Hello

I have a Ton of Word docs that I need to open in Wordpad and then save as a .txt file. I have an app that parses the txt file and loads that data into a DB. If I open .doc file with word and save it as a .txt file it crashes the parser. If I do it with Wordpad it works fine.

I'm looking for a way to automate the process with VB. But, I'm having no luck trying to get wordpad to work with VB.

I've tried to shell wordpad with:

Code:
Shell "wordpad", vbNormalFocus
This gives me an error code 53 File not found.

And with:

Code:
Shell "C:Program FilesWindows NTAccessorieswordpad.exe", vbNormalFocus
This opens up a blank wordpad doc, But I can't find a way to programatically open the doc file and do the save.

and with:

Code:
Shell "C:Program FilesWindows NTAccessorieswordpad.exe " & App.Path & "Worddoc.doc", vbNormalFocus
This one opens wordpad but then wordpad gives the error:
"C:Program
Connot find this file
Pease verify that the correct path and file name are given."

The path is correct to the doc file.

Any Ideas?

Can Wordpad even be manipulated via code?

Thanks

David

Open A Word File In A Ritch Text Box Control
Hello all
I have to open a microsoft word document in a ritch text box(RTF). but in my application it opens word file but in that it display's number of ascii characters. i want to open as it is. so how colud i open a word document .
plz reply me if any know's this
thanks
Dhanu_patil@yahoo.com

HowTo: Open Pure-text Files With Word Using VB?
Hi, I am trying to open a pure-text file known as .sum (summary reports), and because I need to do Office VBA operations, so I assume this is the only way. Here's my code:

Dim wdApp As Word.Application

Private Sub Form_DblClick()
wdApp.Documents.Open FileName:= "C:WorkGetReferenceD6045100-X601319000GB-FT1-0421-C_20050422_081933.sum", _
Format:=FileConverters("WordPerfect6x").OpenFormat

End Sub

How can I correctly use FileConverters so that I can open .sum extension with Word.

PS: I do not need to save the pure-text, so w/e format it opens in is fine, all I need to do is VBA operations with the contents inside

VBA Word Template Word 2000
Help Please!!!

I have written a Letter template an once launched a user form pops up giving you the option to type in your details. Now this all works okay but when you save the template and then re-open the template The userform does not appear allowing you to make chnages to the template. Is there any code or a way in VBA you can get the userform to launch and to load all the informtion first typed into the userform?

Here is my code in the 'My Document' part.

On Error Resume Next
Dim oform As frmletter
Set oform = frmletter

oform.txt10.Text = Format$(Date, "d mmmm yyyy")
oform.Show

If oform.Tag = "OK" Then
' updating bookmark called "TO"
Dim bmrangeTo As Range
Set bmrangeTo = ActiveDocument.Bookmarks("To").Range

bmrangeTo.Text = oform.txt1

ActiveDocument.Bookmarks.Add _
Name:="To", _
Range:=bmrangeTo
Set bmrangeTo = Nothing

' updating bookmark called "TO1"
Dim bmrangeTo1 As Range
Set bmrangeTo1 = ActiveDocument.Bookmarks("To1").Range

bmrangeTo1.Text = oform.txt1

ActiveDocument.Bookmarks.Add _
Name:="To1", _
Range:=bmrangeTo1
Set bmrangeTo1 = Nothing


' updating bookmark called "ADDRESS"
Dim bmrangeAddress As Range

Set bmrangeAddress = ActiveDocument.Bookmarks("Address").Range

bmrangeAddress.Text = oform.txt2

ActiveDocument.Bookmarks.Add _
Name:="Address", _
Range:=bmrangeAddress
Set bmrangeAddress = Nothing

' updating bookmark called "YourRef"
Dim bmRangeRef1 As Range

Set bmRangeRef1 = ActiveDocument.Bookmarks("YourRef").Range

bmRangeRef1.Text = oform.txt8

ActiveDocument.Bookmarks.Add _
Name:="YourRef", _
Range:=bmRangeRef1
Set bmRangeRef1 = Nothing

' updating bookmark called "OurRef"
Dim bmRangeRef2 As Range

Set bmRangeRef2 = ActiveDocument.Bookmarks("OurRef").Range

bmRangeRef2.Text = oform.txt9

ActiveDocument.Bookmarks.Add _
Name:="OurRef", _
Range:=bmRangeRef2
Set bmRangeRef2 = Nothing

' updating bookmark called "DATE"
Dim bmRangeDate As Range

Set bmRangeDate = ActiveDocument.Bookmarks("Date").Range

bmRangeDate.Text = oform.txt10

ActiveDocument.Bookmarks.Add _
Name:="Date", _
Range:=bmRangeDate
Set bmRangeDate = Nothing
ActiveDocument.Bookmarks("StartHere").Range.Select
Set oform = Nothing

Else

Set oform = Nothing

End If
End Sub

Thank you in advance.
TonyD

I Want To Open An Excel Template?
I know that if I have a command button in the following:


Code:
Private Sub Command2_Click()
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
xlSheet.Activate
xlSheet.Application.Visible = True
Exit Sub
End Sub
Then I'll have a brand new Excel spreadsheet to transfer over data.
I have two questions.

1.) How can I pull up a template instead of a whole new document?

2.) How can I pull up a certain file instead of a new document?

Thanks for any help!

I appreciate it!

Sincerely

Open Normal Template In Vb6
Ok...when you open visual basic editor in word will open you a NORMAL project himself. how do i open this NORMAL project in vb6 or where is this project for proggraming the normal template of word

TNX

Template Doesnt Open :(
I'm trying to write a template...Now I've followed the steps as described on:
http://www.fontstuff.com/vba/vbatut09c.htm and saved it all as document template. But if I open the document template, nothing happens (the vba form doesnt appear)..what am i doing wrong ? plz see attachment

Copyright İ 2005-08 www.BigResource.com, All rights reserved