After a tip from cheong00 I discovered I had approached this task in the wrong way.
This is how it should be done:
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Wordprocessing
Imports DocumentFormat.OpenXml.Packaging
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(processDocument("C:\temp\testdoc.docx", "[Webpage]", "Google", "https://www.google.com"), MsgBoxStyle.ApplicationModal + vbOKOnly, "Text replace test")
End Sub
Private Function processDocument(ByVal tDocFilename As String, ByVal tagText As String, ByVal replText As String, ByVal replURL As String) As String
Using doc As WordprocessingDocument = WordprocessingDocument.Open(tDocFilename, True)
Dim mainPart As DocumentFormat.OpenXml.Packaging.MainDocumentPart = doc.MainDocumentPart
Dim textPLaceList As IEnumerable(Of Wordprocessing.Text) = mainPart.Document.Descendants(Of Wordprocessing.Text)()
Try
For Each textPlaceHolder As Wordprocessing.Text In textPLaceList
Dim parent As Wordprocessing.Paragraph = textPlaceHolder.Parent.Parent
If (TypeOf parent Is Wordprocessing.Paragraph) Then
If textPlaceHolder.Text.Contains("[") And textPlaceHolder.Text.Contains("]") Then
Dim newParagraph As Paragraph = getURLParagraph(mainPart, replText, replURL)
parent.Parent.InsertBefore(Of Wordprocessing.Paragraph)(newParagraph, parent)
textPlaceHolder.Remove()
Exit For
End If
End If
Next
processDocument = "OK"
Catch ex As Exception
processDocument = "Could not replace text in document (" & ex.Message & ")"
End Try
End Using
End Function
Private Function getURLParagraph(ByVal mainPart As MainDocumentPart, ByVal urlLabel As String, ByVal urlText As String) As Paragraph
Dim urlExists As Boolean
Dim hRelation As HyperlinkRelationship = Nothing
Dim uri As System.Uri = New Uri(urlText)
For Each hRel As HyperlinkRelationship In mainPart.HyperlinkRelationships
If (hRel.Uri = uri) Then
urlExists = True
hRelation = hRel
Exit For
End If
Next
Dim relationshipId As String
If Not urlExists Then
Dim rel As HyperlinkRelationship = mainPart.AddHyperlinkRelationship(uri, True)
relationshipId = rel.Id
Else
relationshipId = hRelation.Id
End If
Dim newParagraph As Paragraph = New Paragraph(New Hyperlink(New ProofError() With {
.Type = ProofingErrorValues.GrammarStart
}, New Run(New RunProperties(New RunStyle() With {
.Val = “Hyperlnk”}), New Text(urlLabel))) With {
.History = OnOffValue.FromBoolean(True),
.Id = relationshipId
})
Return newParagraph
End Function
End Class
Hope this is of some help to others.
Regards
Peter Karlström