View Single Post
 
Old 01-28-2024, 08:46 AM
ctviggen ctviggen is offline Windows 10 Office 2016
Advanced Beginner
 
Join Date: Feb 2021
Posts: 54
ctviggen is on a distinguished road
Default

I figured it out. If you put "Set aRng = Selection.Range" after "Set openDoc = ActiveDocument" but before you paste into the new document (newDoc), the insertion point comes at the cursor location in the open document. If you move that same statement later, I believe the "Selection" is in newDoc, and then the paste will occur in newDoc. Like this, but I've left all the other stuff in that did not work:


Code:
Sub Example()
    
    Dim newDoc As Document
    Dim openDoc As Document
    Dim aRng As Range
    
    ' See if this sets the open document to openDoc
    Set openDoc = ActiveDocument
    'This should set the insertion point where the cursor currently is
    ' in the open document (openDoc)
    Set aRng = Selection.Range ' Set here before you open the new document
        
    ' Add a new document to store the copied text
    Set newDoc = Documents.Add
    ' This adds with all the formatting, including cross-referencing
    newDoc.Content.Paste
                
    ' Change "X" to "Y"
    With newDoc.Range.Find
        .Text = "X"
        .Replacement.Text = "Y"
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll ' This performs the replacement
    End With
        
    ' Set aRng = openDoc.Range
    ' Set aRng to the current selection in the open document
    ' The following does not work for the currently open document and copies into newDoc
    ' Set aRng = Selection.Range
    ' The following seems like it should work to copy into the current open document (openDoc),
    '    but the text goes into newDoc
    ' Set aRng = openDoc.Application.Selection.Range
    ' The following causes an error
    ' Set aRng = openDoc.Selection.Range
    
    ' Insert the manipulated text at the current cursor location
    ' aRng.Collapse Direction:=wdCollapseEnd
    aRng.FormattedText = newDoc.Range.FormattedText

    'Close that document (without nasty questions)
    Documents(newDoc).Close SaveChanges:=wdDoNotSaveChanges
      
    
End Sub
Reply With Quote