macroapa said:
Hi and sorry for what will be a stupid question, but I just cant suss
it.
I have some code that types text into a document (and performs
multiple other tasks on it), but as I have multiple docs open,
sometimes it types it into the wrong doc. As I understand I need to
use the range object.
My code currently is:
Selection.TypeText Text:="xyz"
How do I convert this so that it always types the text into the
document called "BaseLetter.doc"
Thanks for the help.
Start by assigning each open document to a separate variable of type
Document, at the time the macro either opens or creates that document. Then
you can define a separate range object to use in each document.
Sub Demo()
Dim DocA As Document
Dim DocB As Document
Dim DocC As Document
Dim rgA As Range
Dim rgB As Range
Set DocA = ActiveDocument
' the one that has focus when the macro starts
Set DocB = Documents.Open(FileName:="C:\temp\BaseLetter.doc")
Set DocC = Documents.Add ' how to make a new blank document
Set rgA = DocA.Range ' the whole document A, if you need that
Set rgB = DocB.Bookmarks("Name").Range ' a specific bookmark in B
rgB.Text = "xyz" ' will go into bookmark in document B
End Sub
There are shortcuts you can take, but until you understand what's happening
in a verbose example like this, you risk still getting the wrong place.
A couple of other notes:
- Assigning a string to the .Text member of a range object is preferable to
using the .TypeText method of the Selection because it's much more
predictable. For example, if existing text is selected when you use
..TypeText, that text may or may not be replaced depending on the setting of
an option (Options.ReplaceSelection, which corresponds to the "Typing
replaces selection" item in the Tools > Options > Edit dialog). Forgetting
this may result in a mess in the document. Setting a range's .Text always
replaces anything already in the range; to add the new text before or after
the current range, first use the range's .Collapse method.
- Assigning text to the range of a bookmark will delete the bookmark, which
then needs to be added back. See
http://www.word.mvps.org/FAQs/MacrosVBA/InsertingTextAtBookmark.htm if this
is part of your work.
- If you need to get a range from the current Selection location, you can
use
Set rgB = Selection.Range
but first be sure to check which document contains the Selection, to avoid
nasty surprises.
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.