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

2 Answers 2

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
4
  • 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, 2014 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. Oct 30, 2014 at 10:45
  • @DavidGard Scroll position: stackoverflow.com/a/30765988/600135
    – kol
    Mar 7, 2018 at 16:00
  • Does it mean that we can't get selection of an inactive document?
    – AKd
    Jan 8 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
1
  • Thank you for the suggestion, but that does not seem to be working.
    – David Gard
    Oct 30, 2014 at 12:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.