![]() |
|
#1
|
|||
|
|||
|
Hello, I'm a beginner in VBA and I'm wondering if it's possible to insert a hyperlink after doing a find and replace macro.
I've done a find and replace macro using an Excel list from this thread:https://www.msofficeforums.com/word-...html#post34254 Would it be possible to insert a hyperlink to the replacement texts if a link is inserted to cell adjacent to replace terms? For example, column A = find terms, column B = replace terms, column C = string of link to insert to replace terms. I would appreciate any help!
|
|
#2
|
|||
|
|||
|
Here is a method to process just the active document. You can revise to suit processing an entire folder using Paul's code for an example:
Code:
Option Explicit
Sub FRWithDefinedHyperlinks()
Dim strDataSourcePath As String, strWorksheet As String
Dim strSQL As String
Dim oVBA_LB As Object
Dim lngIndex As Long
Dim strFolder As String, strFile As String, strDocNm As String, wdDoc As Document
Dim oRng As Range
strDataSourcePath = "D:\FRList.xlsx": strWorksheet = "Sheet1"
If Dir(strDataSourcePath) = "" Then
MsgBox "Cannot find the designated workbook: " & strDataSourcePath, vbExclamation
Exit Sub
End If
'Get all data from sheet named "Sheet1", exclude heading row
strSQL = "SELECT * FROM [" & strWorksheet & "$];"
'Create a Listbox object to hold data
Set oVBA_LB = CreateObject("New:{8BD21D20-EC42-11CE-9E0D-00AA006002F3}")
xlFillList oVBA_LB, strDataSourcePath, "True", strSQL
Application.ScreenUpdating = False
Set wdDoc = ActiveDocument
'Process each word from the F/R List
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWholeWord = True
.MatchCase = True
.Wrap = wdFindContinue
For lngIndex = 0 To oVBA_LB.ListCount - 1
.Text = oVBA_LB.List(lngIndex, 0)
While .Execute
wdDoc.Hyperlinks.Add Anchor:=oRng, _
Address:=oVBA_LB.List(lngIndex, 2), _
ScreenTip:=oVBA_LB.List(lngIndex, 3), _
TextToDisplay:=oVBA_LB.List(lngIndex, 1)
Wend
Next
End With
Set wdDoc = Nothing: Set oVBA_LB = Nothing
Application.ScreenUpdating = True
lbl_Exit:
Exit Sub
End Sub
Public Function xlFillList(oListOrComboBox As Object, strWorkbook As String, _
bSuppressHeader As Boolean, strSQL As String)
Dim oConn As Object
Dim oRecordSet As Object
Dim lngNumRecs As Long, lngIndex As Long
Dim strWidth As String
Dim strConnection As String
'Create connection:
Set oConn = CreateObject("ADODB.Connection")
If bSuppressHeader Then
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strWorkbook & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Else
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strWorkbook & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=NO"";"
End If
oConn.Open ConnectionString:=strConnection
Set oRecordSet = CreateObject("ADODB.Recordset")
'Read the data from the worksheet.
oRecordSet.Open strSQL, oConn, 3, 1 '3: adOpenStatic, 1: adLockReadOnly
With oRecordSet
'Find the last record.
.MoveLast
'Get count.
lngNumRecs = .RecordCount
'Return to the start.
.MoveFirst
End With
With oListOrComboBox
.Clear
'Load the records into the columns of the named list/combo box.
.ColumnCount = oRecordSet.Fields.Count
.Column = oRecordSet.GetRows(lngNumRecs)
strWidth = vbNullString
End With
Cleanup:
If oRecordSet.State = 1 Then oRecordSet.Close
Set oRecordSet = Nothing
If oConn.State = 1 Then oConn.Close
Set oConn = Nothing
lbl_Exit:
Exit Function
End Function
Last edited by gmaxey; 09-23-2025 at 02:38 AM. |
|
#3
|
|||
|
|||
|
Hi Greg!
Thank you for taking the time to write the code, and sorry for the late reply. The code works wonderfully! I did make the initial mistake of inserting it to the Excel file, and later figured out that the macro should run from the Word file May I ask why we need a Listbox object to hold data and what the xlFillList function does? Does the code performance differ from Paul's method which defined the column address in Excel (snippets below)? I would like to learn and understand the code better ![]() Code:
' Capture the F/R data.
For i = 1 To iDataRow
' Skip over empty fields to preserve the underlying cell contents.
If Trim(.Range("A" & i)) <> vbNullString Then
xlFList = xlFList & "|" & Trim(.Range("A" & i))
xlRList = xlRList & "|" & Trim(.Range("B" & i))
End If
Next
'Some code here
'Process each word from the F/R List
With wdDoc
Options.DefaultHighlightColorIndex = wdYellow
With .Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.MatchWholeWord = True
.MatchCase = True
.Wrap = wdFindContinue
For i = 1 To UBound(Split(xlFList, "|"))
.Text = Split(xlFList, "|")(i)
.Replacement.Text = Split(xlRList, "|")(i)
.Execute Replace:=wdReplaceAll
Next
End With
|
|
#4
|
|||
|
|||
|
Calinanix
A listbox is typically associated and displayed with a userform. In this case we don't really need to create or display the form a form , but a listbox is very easily populated from Excel or Access using an ADODB connection (you don't have to physically open the Excel file). That is the purpose of the xlFillList function. |
|
#5
|
|||
|
|||
|
Dear Greg,
I see. Thank you again for your time and knowledge! Have a good day
|
|
#6
|
|||
|
|||
|
Dear Greg, or anyone who sees this thread,
Sorry to bother you again regarding this matter. I tried to construct a macro extending Paul's F&R macro with yours. I wanted to run the insert hyperlink code only if the column for hyperlink input (column H) is not empty. Since I wanted the code to run from Excel, I tried to construct the code using a string list rather than a Listbox object & ADODB connection because I wanted to run the macro from Excel. However, I seem to always get an error: Run-time error 4198 "Command Failed" whenever I try to run the macro. What have I done wrong with the code? Code:
Option Explicit
Sub FRandHyperlink()
'Macropod ©2012 from https://www.msofficeforums.com/word-vba/12803-find-replace.html#post34254
'gregmaxey © 2025 from https://www.msofficeforums.com/word-vba/53797-insert-hyperlink-text-replacement-after-find-replace.html
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, wdDoc As Document
Dim xlApp As Object, xlWkBk As Object, StrWkBkNm As String, StrWkSht As String
Dim iDataRow As Long, xlFList As String, xlRList As String, xlHList As String, i As Long
Dim xlFItem As String, xlRItem As String, xlHItem As String
StrWkBkNm = "C:\Users\calista.hadiwarsito\Documents\Simplifikasi PDR\Macro Testing\Input Template Tester.xlsm"
StrWkSht = "Data Input"
If Dir(StrWkBkNm) = "" Then
MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
Exit Sub
End If
On Error Resume Next
'Start Excel
Set xlApp = CreateObject("Excel.Application")
If xlApp Is Nothing Then
MsgBox "Can't start Excel.", vbExclamation
Exit Sub
End If
On Error GoTo 0
With xlApp
'Hide our Excel session
.Visible = False
' The file is available, so open it.
Set xlWkBk = .Workbooks.Open(StrWkBkNm, False, True)
If xlWkBk Is Nothing Then
MsgBox "Cannot open:" & vbCr & StrWkBkNm, vbExclamation
.Quit: Set xlApp = Nothing: Exit Sub
End If
' Process the workbook.
With xlWkBk
'Ensure the worksheet exists
If SheetExists(xlWkBk, StrWkSht) = True Then
With .Worksheets(StrWkSht)
' Find the last-used row in column A.
iDataRow = Sheets("Data Input").Cells(.Rows.Count, "D").End(xlUp).Row ' -4162 = xlUp
' Capture the F/R data.
For i = 1 To iDataRow
' Skip over empty fields to preserve the underlying cell contents.
If Trim(.Range("D" & i)) <> vbNullString And Trim(.Range("E" & i)) = "FR" Then
xlFList = xlFList & "|" & Trim(.Range("D" & i))
xlRList = xlRList & "|" & Trim(.Range("H" & i))
xlHList = xlHList & "|" & Trim(.Range("I" & i))
End If
Next
End With
Else
MsgBox "Cannot find the designated worksheet: " & StrWkSht, vbExclamation
End If
.Close False
End With
.Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
'Exit if there are no data
If xlFList = "" Then Exit Sub
Set wdDoc = Documents.Open(ThisWorkbook.Path & "\Template PDR 3_full.docx", AddToRecentFiles:=True, Visible:=True)
'Process each word from the F/R List
With wdDoc
Options.DefaultHighlightColorIndex = wdYellow
End With
With wdDoc.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.MatchWholeWord = True
.MatchCase = True
.Wrap = wdFindContinue
For i = 1 To UBound(Split(xlFList, "|"))
xlFItem = Split(xlFList, "|")(i)
xlHItem = Split(xlHList, "|")(i)
xlRItem = Split(xlRList, "|")(i)
If xlHItem <> "" Then
.Text = xlFItem
While .Execute
wdDoc.Hyperlinks.Add Anchor:=wdDoc.Range, _
Address:=xlHItem, _
ScreenTip:="", _
TextToDisplay:=xlRItem
Wend
Else
.Text = xlFItem
.Replacement.Text = xlRItem
.Execute Replace:=wdReplaceAll
End If
Next
End With
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub
|
|
| Tags |
| find and replace, hyperlink |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Using find/replace to insert a word while retaining wildcard-found text | paulkaye | Word | 2 | 11-13-2022 03:17 AM |
Find-replace using part of what was found in the replacement text
|
paulkaye | Word | 3 | 12-22-2014 02:52 AM |
Created VBA to Find and Replace in Body, Header and Footer with Highlighting the replacement text
|
QA_Compliance_Advisor | Word VBA | 11 | 09-23-2014 04:40 AM |
| Hyperlink/Data Insert & replace | jclinton | Word | 1 | 09-19-2012 07:22 PM |
Insert text at the end of a sentence Find/Replace
|
AlmostFriday | Word | 6 | 06-17-2012 05:21 AM |