The following procedures illustrate:
Code: Select all
Option Explicit
Sub Demo_LostSelection_AnomolyI()
Dim oRng As Range
Dim oDocTmp As Document
ActiveDocument.Range.Text = "One two three"
ActiveDocument.Words(1).Select
Set oDocTmp = Documents.Add
oDocTmp.Close wdDoNotSaveChanges
'Notice after the procedure runs that the selection is reset to the start of the page.
lbl_Exit:
Exit Sub
End Sub
Sub Demo_LostSelection_AnomolyII()
Dim oRng As Range
Dim oDocTmp As Document
ActiveDocument.Range.Text = "One two three"
ActiveDocument.Words(1).Select
Set oDocTmp = Documents.Add
'The problem seems to manifest from closing the temporary document.
'Set that out, and the selection in the original document is preserved.
'oDocTmp.Close wdDoNotSaveChanges
lbl_Exit:
Exit Sub
End Sub
Sub Demo_LostSelection_AnomolyIII()
Dim oRng As Range
Dim oDocTmp As Document
Dim i
ActiveDocument.Range.Text = "One two three"
ActiveDocument.Words(1).Select
Set oDocTmp = Documents.Add
'The problem seems to manifest from closing the temporary document.
oDocTmp.Close wdDoNotSaveChanges
'The problem does not persist if there is a breakpoint in the code. Let the code
'run to the stop then run to end.
Stop
lbl_Exit:
Exit Sub
End Sub
Sub Demo_LostSelection_AnomolyIV()
Dim oRng As Range
Dim oDocTmp As Document
ActiveDocument.Range.Text = "One two three"
ActiveDocument.Words(1).Select
Set oDocTmp = Documents.Add
'The problem seems to manifest from closing the temporary document.
oDocTmp.Close wdDoNotSaveChanges
'The problem persists even if you attempt to reselect the original selection after closing the temporay file.
ActiveDocument.Words(1).Select
lbl_Exit:
Exit Sub
End Sub
Sub Demo_LostSelection_AnomolyV()
Dim oRng As Range
Dim oDocTmp As Document
ActiveDocument.Range.Text = "One two three"
ActiveDocument.Words(1).Select
Set oDocTmp = Documents.Add
'The problem seems to manifest from closing the temporary document.
oDocTmp.Close wdDoNotSaveChanges
'... even though that text was still selected
MsgBox Selection.Text
'... or if you attempt to make another selection
ActiveDocument.Words(3).Select
MsgBox Selection.Text
'For whatever reason, closing the temporary document and letting the procedure run to completion
'without a breakpoint destroys the selection (resets it to the top of the page).
lbl_Exit:
Exit Sub
End Sub
Why does adding the breakpoint (Stop) prevent this behavior?
Anyone know of a solution to prevent this behavior without resorting to breakpoint?
cross posted at: http://www.vbaexpress.com/forum/showthr ... on-Anomoly and https://www.msofficeforums.com/word-vba ... post182059