Why does Document.SetRange not set the range!?

R

Robin Tucker

Given a field code (called theField) I have obtained from the Fields
collection of my document, why is it that I am unable to set "insertion
point" for an item for the given document to be the end of the field code?

My code looks something like this:

m_WordDocument.Range.SetRange(theField.Result.Start, theField.Result.End)
m_WordDocument.Range.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
m_WordDocument.Range.Move(Word.WdUnits.wdCharacter, 1)


theField.Result.Start = 120 and theField.Result.End = 149. Before calling
"SetRange", the document range is 0..480. Strangely, after calling
"SetRange", the document range has not changed, even though I've passed in
120 and 149! It seems that "Range" stores the extent of the document, from
0...n. I want to be able to insert things at specific positions within the
document.

Previously I was doing this using Application.Selection.Range etc. However,
it quickly became apparent that Application.Selection refers to the
currently active document, which would knobble my application as soon as the
user opened another instance of word.

How can I manipulate the insertion point for the current document?

Thanks for any help you can give me.



Robin
 
J

Jay Freedman

Hi Robin,

m_WordDocument.Range is *by definition* the range of the entire document.
Calling .SetRange on it has no effect (though I'll admit I know why it
doesn't trigger an error). You also can't collapse or move the document's
range. Instead, you need to declare a separate Range object and manipulate
that.

When you do so, you don't need .SetRange (which is in my opinion a largely
useless method) -- you can simply assign one range to another like this:

Dim oRg As Range

Set oRg = theField.Result
oRg.Collapse wdCollapseEnd
oRg.Move wdCharacter, 1

This is native VBA, but you should be able to translate it to VB.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top