11

I have a macro that scans my document for Heading 1 styles, and consequently the cursor is moved to after the last match.

I'm trying to capture the location of the cursor before this scan occurs, and then return to that position after it has finished. How do I do this?

I found this answer on SO, but it's not working (No error, it just doesn't do anything.)

Application.ScreenUpdating = False ' Turn screen updates off so the user will not know that the cursor has moved

Dim currentPosition As Long
currentPosition = Selection.Range.Start

{... do stuff here ...}

Selection.Range.Start = currentPosition

Application.ScreenUpdating = True
Community
  • 1
  • 1
David Gard
  • 11,225
  • 36
  • 115
  • 227

2 Answers2

22
Dim currentPosition As Range
Set currentPosition = Selection.Range 'pick up current cursor position

' do stuff — cursor gets moved around

currentPosition.Select 'return cursor to original position
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
  • 3
    Thank you, that works. I do have one very petty request, if you happen to know the answer though - Even though the selection remains as it was before, the screen moves so that the selection is at the top of the screen. Is there anyway to also save the screen position? Thanks. – David Gard Oct 30 '14 at 10:35
  • Good question... I suggest you post a new question. I don't know off the top of my head; you will get more attention with a new question. – Jean-François Corbett Oct 30 '14 at 10:45
  • @DavidGard Scroll position: https://stackoverflow.com/a/30765988/600135 – kol Mar 07 '18 at 16:00
  • Does it mean that we can't get selection of an **inactive** document? – AKd Jan 08 '23 at 17:25
2

You could also use bookmarks:

Sub test()
    ThisDocument.Bookmarks.Add ("xx")
    {... do stuff here ...}
    ThisDocument.GoTo what:=wdGoToBookmark, Name:="xx"
End Sub
iDevlop
  • 24,841
  • 11
  • 90
  • 149