Reputation: 816
Currently I am building a Word document which is being filled by custom fields from a third party with the actual data.
The proces on filling the document is as follow:
- From third party program generate document -> 2. Word opens, I can execute my VBA code -> 3. document closes again -> 4. document opens and is being filled with the data from third party program -> 5. document gets exported to Outlook.
So far this works fine, I can mimic the third party their Word fields with VBA code.
Now I would like to use some of this data to generate a unique url. The url would look as follow: http://example.com?q1=field1&q2=field2 (in this example the only thing in the document also).
What I am trying to do now is to replace 'field1' or 'field2' with the actual necessary Word field (dynamically). This doesn't seem to work for URL's (works fine seperatly). The code would be executed at the second part of the proces.
To replace certain tags with fields I use the following code, I was hoping that it would also work for URLs but that doesnt seem to be the case.
item would have as input:
item(0) = "field1" - tag name,
item(1) = "Example" - First part of the field,
item(2) = "<<contract_example>>" - Second part of the field
Private Sub TranslateItem(item() As String)
Selection.HomeKey wdStory
Selection.find.Text = item(0)
Dim holder As Boolean
holder = True
Do While holder
Dim tempholder As Boolean
tempholder = Selection.find.Execute
If tempholder Then
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:=item(1) & item(2), PreserveFormatting:=False 'add field
Else
holder = False
End If
Loop
End Sub
This code doesn't seem to replace the actual part of the URL but just the text. I came across this (How to programmatically edit all hyperlinks in a Word document?) link on how to edit a url, but I have no clue on how to search and replace the tag and add a field in that example.
Upvotes: 0
Views: 99
Reputation: 176169
You can iterate over all hyperlinks in the document and then modify their properties as you need it:
Sub ModifyHyperlinks()
Dim link As Hyperlink
For Each link In ActiveDocument.Hyperlinks
link.Address = Replace(link.Address, "q1=", "q1=field1")
link.Address = Replace(link.Address, "q2=", "q2=field2")
Next
End Sub
Upvotes: 3