Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101
Word FAQ - Word VBA 101 Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Go Back  Xtreme Visual Basic Talk > > > > Word FAQ - Word VBA 101


Closed Thread
 
Thread Tools Display Modes
  #1  
Old 12-02-2003, 02:58 PM
Wamphyri's Avatar
WamphyriWord FAQ - Word VBA 101 Wamphyri is offline
Variable not defined

Retired Moderator
* Guru *
 
Join Date: Apr 2002
Location: Ottawa, Ontario
Posts: 4,793
Default Word 101


Due to popular demand, over the next couple weeks I'm going to post a couple of basic Word tutorials. All tutorials are going to be written from Word 2000, however, I will try and make sure that all code will be able to run on both Word 97 and Word 2002. The first tutorial will be simply about creating and writing a word document, using both early and late binding.

The main benefit of early binding is speed, while the main benefit of late binding is compatibility over different versions of the bound application (in this case Word).

In order to use early binding you must add a reference to the Object library.
If you are using VB 6 then you do this by going to:
Projects -> References -> Microsoft Word Object X.0 Library
(Where X is the version of word: 97 = 8.0; 2000 = 9.0; 2002 = 10.0)

If you are using VBA then you do this by going to:
Tools -> References -> Microsoft Word Object X.0 Library

If you are using late binding you do not add references these libraries.

One of the side benefits of early binding is that it allows view the members of object when you hit ‘.’ . That is why during development of an application I always use early binding even if I plan to distribute the application using late binding.
Code:
Sub WordHelloWorldEarlyBinding() Dim objWdApp As Word.Application Dim objWdDoc As Word.Document Dim objwdRange As Word.Range 'Create instance of Word Application Set objWdApp = New Word.Application 'Add new document Set objWdDoc = objWdApp.Documents.Add 'or you could open a document using .Open 'Set objWdDoc = objWdApp.Documents.Open(FileName:="C:\testdoc.doc") 'Set the range equal to the entire word doc Set objwdRange = objWdDoc.Content 'Insert Hello World objwdRange.Text = "Hello World" 'We forget punctuaction so let's add it after World objwdRange.InsertAfter "!" 'Make word visible objWdApp.Visible = True 'Saves document as C:\testdoc.doc objWdDoc.SaveAs FileName:="C:\testdoc.doc" 'To quit word use 'objWdApp.Quit Set objwdRange = Nothing Set objWdDoc = Nothing Set objWdApp = Nothing End Sub Sub WordHelloWorldLateBinding() Dim objWdApp As Object Dim objWdDoc As Object Dim objwdRange As Object 'Create instance of Word Application Set objWdApp = CreateObject("Word.Application") 'From here on the code is the same End Sub
One additional comment about early and late binding. When using early binding you can use constant define by Word's Object Library, however when using late binding you must either define the constants yourself or use the actual values of the constants.
For example:
Code:
'This is acceptable in early binding Range.Collapse wdCollapseStart 'In late binding you would need to assign the value Range.Collapse 1

A little more info on early and late binding.
__________________
-Carl

Last edited by Wamphyri; 11-22-2004 at 02:05 PM.
  #2  
Old 12-12-2003, 09:13 AM
Wamphyri's Avatar
WamphyriWord FAQ - Word VBA 101 Wamphyri is offline
Variable not defined

Retired Moderator
* Guru *
 
Join Date: Apr 2002
Location: Ottawa, Ontario
Posts: 4,793
Default Basic Find and Replace

One of the more common questions is about using the Find and Replace objects. The basic concept to using the Find and Replace objects is as follows:
1. Define your search range.
2. Clear the formatting for the Find and Replace objects
3. Define your Find parameters
4. Define any Replace parameters
5. Execute the operation
Code:
Dim objWdApp As Word.Application Dim objWdDoc As Word.Document Dim objWdRange As Word.Range Set objWdApp = New Word.Application Set objWdDoc = objWdApp.Documents.Open(FileName:="C:\testdoc.doc") objWdApp.Visible = True 'Set the range equal to the range to preform your search on. 'In this case it will be the content of the word document. 'This is the equivalent of objWdDoc.StoryRanges(wdMainTextStory) Set objWdRange = objWdDoc.Content 'The most common use is to find one word and replace it with another With objWdRange.Find ' to ensure that unwanted formats aren't included as criteria .ClearFormatting .Replacement.ClearFormatting .Text = "lost" .Replacement.Text = "found" .Execute Replace:=wdReplaceAll 'or you can use the execute parameters '.Execute findtext:="lost", replaceWith:="found", Replace:=wdReplaceAll End With 'Another common use is to find a word and change the formatting 'Reset the search range. Set objWdRange = objWdDoc.Content With objWdRange.Find ' to ensure that unwanted formats aren't included as criteria .ClearFormatting .Replacement.ClearFormatting .Text = "found" .MatchCase = True 'Make found bold and italic With .Replacement.Font .Bold = True .Italic = True End With .Execute Replace:=wdReplaceAll End With Set objWdRange = Nothing Set objWdDoc = Nothing Set objWdApp = Nothing
You can also do searches based on the Font. In this example it deletes everything in Bold font.
Code:
With objWdRange.Find ' to ensure that unwanted formats aren't included as criteria .ClearFormatting .Replacement.ClearFormatting 'You don't care what the text is .Text = "" 'Find the bold text .Font.Bold = True 'Delete the text found .Replacement.Text = "" 'delete all bold text .Execute Replace:=wdReplaceAll .Font.Name End With Set objWdRange = Nothing
__________________
-Carl

Last edited by Wamphyri; 04-12-2004 at 08:47 AM. Reason: added format searching.
  #3  
Old 12-12-2003, 02:24 PM
Wamphyri's Avatar
WamphyriWord FAQ - Word VBA 101 Wamphyri is offline
Variable not defined

Retired Moderator
* Guru *
 
Join Date: Apr 2002
Location: Ottawa, Ontario
Posts: 4,793
Default Advanced Find and Replace (Wildcards)

The Find and Replace Objects change be much more useful (and powerful) if you know how to use wildcards.
The word uses the following wildcards:
Code:
?	Any single character
*	Any string of characters
[ ]	One of the specified characters
[-]	Any single character in this range
[!]	Any single character except the characters inside the brackets
[!x-z]	Any single character except characters in the range inside the brackets
{n}	Exactly n occurrences of the previous character or expression
{n,}	At least n occurrences of the previous character or expression
{n,m}	From n to m occurrences of the previous character or expression
@	One or more occurrences of the previous character or expression
<	The beginning of a word
>	The end of a word
^w      1 or more spaces
For example adding one to any number in a document.
1 will become 2
13 will become 14
6th will become 7th
Code:
Dim objWdRange As Word.Range Dim bFound As Boolean Set objWdRange = objWdDoc.Content Do With objWdRange.Find 'Clear the formatting .ClearFormatting .Replacement.ClearFormatting .MatchWildcards = True 'Find word begining with a digit then any # of characters then ' ending with a space or a period .Text = "<[0-9]*[ .]" 'Find it, objwdrange is changed to found item bFound = .Execute 'Exit if nothing found If Not bFound Then Exit Do End If 'Replace the found item with found item +1 .Execute Replace:=wdReplaceOne, replacewith:=CStr(Val(objWdRange.Text) + 1 _ & Mid$(objWdRange.Text, Len(CStr(Val(objWdRange.Text))) + 1)) 'Reset objwdrange to continue search after previously found item Set objWdRange = objWdDoc.Range(objWdRange.Start + 1, objWdDoc.Range.End) End With Loop Set objWdRange = Nothing
Another useful find and replace function is the use of parenthesis in the find function and the use of \# in the replace. Using this you can switch the places of the found characters in the parenthesis
A simple example of switching the places of second and first
Code:
Dim objWdRange As Range Set objWdRange = objWdDoc.Content With objWdRange.Find .ClearFormatting .Replacement.ClearFormatting .MatchWildcards = True .Text = "(second) and this (first)" .Replacement.Text = "\2 and this \1" 'Will produce: first and this second .Execute Replace:=wdReplaceAll End With Set objWdRange = Nothing
Edit:
Feel free to PM me with suggestions for future Word 101 tutorials or if you'd like to submit a tutorial of you own.
__________________
-Carl

Last edited by Wamphyri; 02-10-2004 at 02:57 PM. Reason: Added ^w wildcard
  #4  
Old 02-13-2004, 02:57 PM
Wamphyri's Avatar
WamphyriWord FAQ - Word VBA 101 Wamphyri is offline
Variable not defined

Retired Moderator
* Guru *
 
Join Date: Apr 2002
Location: Ottawa, Ontario
Posts: 4,793
Default Is the word document open?

Another common question: Is how do I check if the document is opened already or in use by someone else?

Here is a little function I use to test if the file is locked.
Code:
Public Function IsFileLocked(strFileName As String) As Boolean On Error Resume Next Dim FF As Integer FF = FreeFile 'An error occurs if the document is currently open. Open strFileName For Binary Access Read Lock Read As #FF Close #FF 'Check for Error If Err.Number Then Err.Clear IsFileLocked = True End If End Function
__________________
-Carl

Last edited by Wamphyri; 08-30-2004 at 02:02 PM. Reason: spelling mistake (should have used word's spellchecker before posting) ;)
  #5  
Old 08-17-2004, 01:24 PM
Wamphyri's Avatar
WamphyriWord FAQ - Word VBA 101 Wamphyri is offline
Variable not defined

Retired Moderator
* Guru *
 
Join Date: Apr 2002
Location: Ottawa, Ontario
Posts: 4,793
Default

There seems to be a number of posts asking about getting the number of replacements when doing a find/replace operation. The unfortunate thing is that you can't get the number of replacements using wdReplaceAll, however you can loop using wdReplaceOne and using a counter get the number of replacements.
Code:
Dim objWdApp As Word.Application Dim objWdDoc As Word.Document Dim objWdRange As Word.Range Dim bFound As Boolean, i As Long Set objWdApp = New Word.Application Set objWdDoc = objWdApp.Documents.Open(FileName:="C:\testdoc.doc") objWdApp.Visible = True 'start counter at -1 i = -1 Do Set objWdRange = objWdDoc.Content With objWdRange.Find .ClearFormatting .Replacement.ClearFormatting 'Check if word is found bFound = .Execute(findtext:="lost", replaceWith:="found", Replace:=wdReplaceOne) 'increment counter i = i + 1 End With Loop While bFound MsgBox CStr(i) & " replacements made." Set objWdRange = Nothing Set objWdDoc = Nothing Set objWdApp = Nothing
__________________
-Carl
Closed Thread


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Returning control (Focus) to Word from Excel new2vba Word, PowerPoint, Outlook, and Other Office Products 6 02-19-2009 10:30 AM
MS Word & Visual Basic - Need Ideas wagb4 Word, PowerPoint, Outlook, and Other Office Products 2 08-12-2003 06:07 AM
how to create pop-up menu/list box in word document hubong Word, PowerPoint, Outlook, and Other Office Products 0 06-30-2003 10:20 AM
popup menu in word document hubong Word, PowerPoint, Outlook, and Other Office Products 0 06-28-2003 11:00 PM
Palindrome word Steve_Ignorant General 9 11-19-2002 07:55 AM

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101 Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101 Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
 
Word FAQ - Word VBA 101
Word FAQ - Word VBA 101
 
-->