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

Thank you. I _think_ I'm doing that. Here is the code. I cut the code down, because it's doing a lot of search/replace, so the part where there is finding X and replacing with Y is done multiple times. There's other code, too, but I cut that out. This code is what I just tried, with a break point at the statement that closes the new document. Everything works, but the pasted in/revised material gets pasted to the new document (newDoc) and not into the open document (openDoc), which is where I want it.


I just tried it using the "aRng.Collapse Direction:=wdCollapseEnd", and the same thing happens: the revised material gets pasted to the end of the new document (newDoc).



To me, this seems like aRng is set to the open document, and the statement "aRng.FormattedText = newDoc.Range.FormattedText" should put the revised material _somewhere_ in the open document, but it gets put into the new document instead.



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
        
    ' 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