Microsoft Word-  Return to Previous Cursor/Edit Position Using A Button

Jason Steward
Jason Steward used Ask the Experts™
on
I have a Definitions section in my Word document.  I am using Office 365.  The document is an owner's manual, and I am referencing the same definitions multiple times.  The definitions are 200 pages past the primary references.  I'd like to be able to click on a hyperlink taking me to the definition of a word (already done that...  easy), THEN once I'm there, I'd like to click on a button or a hyperlink to take me back to the original position/cursor location/page regarless of where in the document user was reading on prior to navigating to the definition of a key term.

I tried using a button with SendKeys in VBA:  
Private Sub CommandButton1_Click()

    VBA.SendKeys ("{Ctrl}{Alt}{Z}")
    
End Sub

Open in new window

I get a Runtime Error #5 with this, "Invalid procedure call or argument".

My first preference would be to hyperlink to return to previous page, but I can't seem to find any way to accomplish this.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
in any Word document, shift-F5 will bring you back to the last 3 positions of the cursor
Try this:
Private Sub CommandButton1_Click()

    Application.GoBack
    
End Sub

Open in new window

Paul

Author

Commented:
Thanks Flyster!  That's the kind of thing I was looking for.  Much easier to have a user click a button that says "Back" or "Return" than it is to teach random people you don't know how to hold down Shift and F5.  I used your code and didn't get an error message, but it didn't do anything.  When reader clicks a hyperlink from top of document bringing them to the definitions page, pressing the "Back" button does nothing.  It doesn't bring them back to where they were.  So I tried the Shift + F5 as SendKeys and got the same Invalid Procedure error message as mentioned in my original post.
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

The VBA code for Shift F5 is:
VBA.SendKeys ("+{F5}")

Open in new window

Are the hyperlinks to the definitions located on the same page? If so, you can put a bookmark on that page and use this code for your back button:
Selection.GoTo What:=wdGoToBookmark, Name:="Top"

Open in new window

Just change the word "Top" to whatever you name your bookmark.

Author

Commented:
Holding Shift and pressing F5 works, but the code
 
Private Sub CommandButton1_Click()
    VBA.SendKeys ("+{F5}")
End Sub

Open in new window

does nothing when the button is pressed.

I think what I'm going to do is make a text box and create hyperlinks to various pages towards the top of the document.  That way after users click to see the definition they can click to get at least close to where they were reading before.  It just seems crazy to me there isn't a common solution to return readers without a background in computer science to a previous location in a document...

Author

Commented:
One more note for anyone following behind this who wants to keep trying something to make this work...

The Shift + F5 suggestion above would return a user to previous edit points according to what I've read online.  If you are creating a user guide like me, users would not be editing the guide so that wouldn't work.  Similarly, I also found a method online using {Ctrl}{Alt}{Z}, but that returns users to previous cursor position and wouldn't work for a user guide.  What is really needed is something to return users to the previous view...  because users of the guide aren't clicking and editing, they're reading when they click on the hyperlink and I'm not so sure the cursor is changed when clicking on the hyperlinks.  

ALT+LEFT ARROW returns to previous view and seems to be perfect for navigating through hyperlinks.  However, I tried this code:
Private Sub CommandButton1_Click()
        VBA.SendKeys "%{LEFT}", True 
End Sub

Open in new window

and while it works manually typed from a keyboard, the SendKeys method does nothing...  no error, just does nothing when button is pressed.  I'm possibly not executing this right.  Maybe someone someday can figure out how to make it work and change MS Word forever...
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
When you say "pressing the "Back" button does nothing", do you mean the button as described in https://cybertext.wordpress.com/2010/04/21/word-add-a-back-button-to-the-toolbar/ ? Because that one should do the same as Alt-Csr Left.

Author

Commented:
No.  I meant the button I created as per my description which I labeled "Back".  The button should take me to the previous page I was viewing before going to the hyperlink to see a definition in another part of the 1,000+ page document.

Just imagine yourself as a standard user with enough computer knowledge to turn on a computer and open a file for viewing.  The primary reason the user is consulting with this guide is because they are not an advanced computer person.  I will never have a chance to speak with or instruct these people on how to hold down keys, press CTRL, and other secret methods of navigating around a document.  I simply need them to click a hyperlink to see a definition (that's located at bottom of document), then they can click on a button (or a link) that returns them to their previous page.
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
It does not look like you can run a macro to simulate Alt-L (WebGoBack). So all I can think of is, as mentioned above, to replace the jump action to the dscription by code creating a pre-defined fixed bookmark (say YourBookmark), and then having a button executing Selection.GoTo what := wdGoToBookmark, name := YourBookmark to jump back again.

Author

Commented:
I read some things on the bookmark, but I couldn't come up with a complete understanding of the code so that I could customize that solution for my particular document and need.  I'm just not that advanced.  Any ideas on another approach that show a user a Definition of a word when user clicks on the word?
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
Sorry - no.
i imagine that you have seen this:
Create or run a macro
Record a macro with a button

i put the button on the QAT (Quick Access Toolbar) and it works. However, i don't know if it will show up ob the QAT of another computer just by opening the document

i included the document as an example
darktable-workflow.docx
Consultant and developer
Commented:
I found quite a neat way to do this, which I've illustrated in the attached macro-enabled document.

The code takes advantage of the fact that you can access certain "events" in Word by attaching a Class Module to your document capable of responding to "SelectionChange" "BeforeDoubleClick" etc events.

In the example I attached the code to the double-click event.

When the document opens, the Document_Open() routine in module ThisDocument calls routine "InitHyper" in the mHyper code module. This initialises the class module and also creates/initialises a public variable called "bkReturnTo". This references a Word bookmark called "qBack", which the code creates if it doesn't already exist.

It's better to put InitHyper in a regular code module in case your code crashes at some point, which will lose you access to the class module events. You can for instance put a button in the Word document to re-initialise without having to close and re-open the document.

Option Explicit

'public variables
Public wApp As cWordApp
Public bkReturnTo As Bookmark
Public wDoc As Document


Sub InitHyper()
Dim hh As Hyperlink

Set wDoc = ActiveDocument

'set up wApp to reference class module cWordApp
If (wApp Is Nothing) Then
Set wApp = New cWordApp
'assign the wApp.appWord variable to the word application itself
Set wApp.appWord = Word.Application
End If

'initialise the return bookmark
On Error Resume Next
Set bkReturnTo = wDoc.Bookmarks("qBack")
If (bkReturnTo Is Nothing) Then
'create a bookmark, which just references the start of the document
Set bkReturnTo = wDoc.Bookmarks.Add("qBack", wDoc.Range(0, 1))
End If

End Sub

Open in new window


Step Two is the code in the class module which reacts to a double-click. This code does not require you to insert ANY hyperlinks from your main text to reference your definitions.

Instead it does the following:
  • Reads the word at the point you have double clicked
  • Changes the Word "range" referenced by the bkReturnTo bookmark to point to this word
  • Jumps to a pre-defined bookmark in the document called "Definitions" (code won't work without this bookmark)
  • Skips the return hyperlink in the next line
  • Loops through all the following lines checking the first word against the target word you've double-clicked
  • Highlights the definition if found
  • Stops when it reaches the return hyperlink at the end

Both the return hyperlinks in the example point to the bookmark "qBack" (bkReturnTo). So when you click either, it returns to that bookmark, which we have dynamically re-defined.

I tweaked the code so you can find definitions from within definitions without losing the starting point in the main text. So in the demo, I added a definition for "Canis Lupus" which is not referenced in the main text but is referenced in two of the definitions.

Option Explicit
'variable to allow us to access Word events, initialed in ThisDocument code module when file is opened
Public WithEvents appWord As Word.Application

 
Private Sub appWord_WindowBeforeDoubleClick(ByVal Sel As Selection, Cancel As Boolean)
Dim wPara As Paragraph
Dim bkDef As Bookmark
Dim sCheck As String, sDef As String
Dim bStop As Boolean

On Error GoTo errortrap

Cancel = True 'cancel built in double-click

'modify return bookmark (created in InitHyper in mHyper module)
'setting its target range to whatever word has been double-clicked
'but DON'T do this if the double-clicked word is itself in the definitions section:

Set bkDef = wDoc.Bookmarks("Definitions") '- document MUST contain a bookmark called "Definitions"
If Sel.Start < bkDef.Range.Start Then
bkReturnTo.Start = Sel.Range.Words(1).Start
bkReturnTo.End = Sel.Range.Words(1).End
End If

'get the word for which definition is sought as uppercase word, trim spaces
sCheck = UCase(Trim(Sel.Words(1)))

'go to definitions, using bkDef bookmark
Set wPara = bkDef.Range.Paragraphs(1)
'next para (contains return hyperlink in example, so skip it)
Set wPara = wPara.Next
Do
'loop through definitions
Set wPara = wPara.Next
    'stop at end of document as a precaution
    If (wPara Is Nothing) Then
    bStop = True
    Else
    'get first word as uppercase
    sDef = UCase(Trim(wPara.Range.Words(1)))
    'remove colon
    
    'if definition matches word then select the whole paragraph
        If sDef = sCheck Then
        wPara.Range.Select
        Exit Do
        End If
    
        'check for end of definitions
        If wPara.Range.Hyperlinks.Count = 1 Then
            If wPara.Range.Hyperlinks(1).TextToDisplay = "Back to text" Then
            bStop = True
            End If
        End If
    'check for end of document
    End If

Loop Until bStop
Exit Sub

errortrap:
MsgBox ("Error looking for definition")

End Sub

Open in new window


This demo only works for single words. But it could easily be tweaked to use a button that references whatever has been selected. That would avoid the potential vulnerability of using the class module altogether, and would allow you to add enhanced features such as "Can't find a definition for 'dog leg', showing definition for 'dog' instead"...

Hope this helps.
definition-test.docm

Author

Commented:
Thanks!  I'll try both of these!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial