ChimpanA
ChimpanA

Reputation: 3

How to get text from a Word document into another Word Document

I have two Word documents that both contain one word in each document. I have third document that needs to pull each word from the two documents and edit all hyperlinks in the document using the replace function. The replace function works if I enter a string into the function but does not work if when trying to pull the two words from the documents

Public Sub Document_Open()
    Dim x As Document

    Set newSource = Application.Documents.Open("\\t1dc\Everyone\Ben\ns.docx", ReadOnly:=True, Visible:=False)
    Set oldSource = Application.Documents.Open("\\t1dc\Everyone\Ben\os.docx", ReadOnly:=True, Visible:=False)

    Dim newServer As Range
    Set newServer = newSource.Content

    'Test using message box
    MsgBox newServer

    Dim oldServer As Range
    Set oldServer = oldSource.Content

    'Test using message box
    MsgBox oldServer

    For Each h In ActiveDocument.Hyperlinks
           h.Address = Replace(h.Address, oldServer.Text, newServer.Text)
           MsgBox h.Address
    Next

    newSource.Close
    oldSource.Close

    Set x = Nothing
End Sub

Upvotes: 0

Views: 84

Answers (2)

ChimpanA
ChimpanA

Reputation: 3

Yes thank you!

Removed from end of string and it works

Dim oldS As String oldS = Left(oldServer.Text, Len(oldServer.Text) - 1)

Upvotes: 0

Chris
Chris

Reputation: 3529

Check the length of oldServer and newServer, because you're also pulling in the \r that is at the end of a line.

Upvotes: 0

Related Questions