vbarangems-word

Word|VBA - Range.Goto - How to make it work properly?


My test scenario: I'm in Outline view. I have loaded a range from a bookmark into a variable. I want to do the following actually:

dim StartRange as range, nowLevel as integer, startLevel as integer
set StartRange  = Selection.range
nowLevel = StartRange.Paragraphs(1).OutlineLevel
Do    
    StartRange.GoTo What:=wdGoToHeading, Which:=wdGoToPrevious, Count:=1
    nowLevel = StartRange.Paragraphs(1).OutlineLevel
    If nowLevel < startlevel Then ActiveWindow.View.ExpandOutline
Loop Until nowLevel = 1

I have manually debugged the code and used Startrange.select to check where the range object stands. It turned out that it does not move at all. I have tested then separately, and my impression is that Range.goto does not work at all as it never moves itself anywhere. (While doing the same things with Selection.goto does move...)
What am I missing out on?
Edit:
I have added more details to my code snippet above; this should be enogh to run a test for anybody, however the problem is GENERAL for me for any random ranges in usecases (when being on Outline view, either AllLevelsVisible or Collapsed): "StartRange.GoTo What:=wdGoHeading, Which:=wdGoToPrevious, Count:=1"
I have actually solved my original problem now, using selection instead of range, but it would still be great to know for later, what is the problem with range.goto
My other thread with the workaround: Word | VBA - How to start Word in Outline view - opened exactly where you left off?


Solution

  • In your code you use StartRange.GoTo, but your next line uses StartRange again, which just takes the original value.

    Perhaps:

    Set newRange = StartRange.GoTo(What:=wdGoHeading, Which:=wdGoToPrevious, Count:=1)
    nowLevel = newRange.Paragraphs(1).OutlineLevel
    

    Depending on what you want to do, the following may be more applicable:

    Set StartRange = StartRange.GoTo(What:=wdGoHeading, Which:=wdGoToPrevious, Count:=1)
    nowLevel = StartRange.Paragraphs(1).OutlineLevel
    

    Edit: Additional information based on a question in the comments.

    Some range methods (such as MoveStart and Expand) work to actively modify the range parameters. The GoTo method is a function that returns a Range object rather than activity modifying the referenced object. However, MSDN documentation is not clear about this latter part and implies that using the GoTo method moves the range. GoTo does move the insertion point, but this is not the same as moving a Range.

    Soapbox: I am not happy with the new MSDN content - it is now bland and provides only basic descriptions. The older in-depth information (including limitations, edge cases and potential error factors) is being edited out - probably seen as an improvement by some.