Microsoft Office Forums

Go Back   Microsoft Office Forums > >

Reply
 
Thread Tools Display Modes
  #1  
Old 02-23-2023, 12:21 AM
syl3786 syl3786 is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Advanced Beginner
How to export hyperlinks from Excel to Word?
 
Join Date: Jan 2023
Posts: 97
syl3786 is on a distinguished road
Default How to export hyperlinks from Excel to Word?

Hi Community,

I have an Excel file containing hyperlinks addresses and the name of the hyperlinks.
(Column A are the texts, and Column B are the URLs)

I want to replace those texts in a Word Document with the hyperlinks associated with those display texts.

I wrote the below code, which can add a hyperlink to text individually. However, over 500 documents need to add hyperlinks to the texts. And each document contains at least 50 texts and needs to add hyperlinks.

Is there any method to do it faster? Your help will be much appreciated.



Code:
Sub TextFindAndHyperlink()

    Dim query As String
    Dim SearchRange As Range
    Dim SearchText As String
    Dim WebAddress As String
    
    query = InputBox("Texts to replace as hyperlinks")
        If Not query = vbNullString Then
    
    Set SearchRange = ActiveDocument.Range
    SearchText = Replace(query, " ", "+")
    
    WebAddress = InputBox("Please paste the hyperlink")
    If Not WebAddress = vbNullString Then
    
    With SearchRange.Find
        Do While .Execute(SearchText, , True, , , , True) = True
            With SearchRange
                .Hyperlinks.Add SearchRange, WebAddress
            End With
            SearchRange.Collapse wdCollapseEnd
        Loop
    
    MsgBox ("The hyperlink is added to the text")
        
    End With
    
    End If
    End If
    
End Sub
Reply With Quote
  #2  
Old 02-23-2023, 02:27 AM
gmayor's Avatar
gmayor gmayor is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Expert
 
Join Date: Aug 2014
Posts: 4,137
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

Used in conjunction with Document Batch Processes the following custom process - AddHLinks - will add the links associated with the texts in your Worksheet.
Change the path of the workbook and the worksheet name as appropriate:
Code:
Option Explicit

Const strWorkbook As String = "E:\Path\Example.xlsx"        'The path of the workbook
Const strSheet As String = "Sheet1"        'The name of the worksheet

Sub AddHLinks(oDoc As Document)
Dim Arr() As Variant
Dim i As Long
Dim oRng As Range
Dim sFindText As String
Dim sReplaceText As String
    Arr = xlFillArray(strWorkbook, strSheet)
    For i = 0 To UBound(Arr, 2)
        sFindText = Arr(0, i)
        sReplaceText = Arr(1, i)
        Set oRng = oDoc.Range
        With oRng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            Do While .Execute(findText:=sFindText, _
                              MatchWholeWord:=True, _
                              Forward:=True, _
                              Wrap:=wdFindStop) = True
                oRng.Hyperlinks.Add oRng, sReplaceText
                oRng.End = oRng.End + 1
                oRng.Collapse wdCollapseEnd
                DoEvents
            Loop
        End With
    Next
lbl_Exit:
    Exit Sub
End Sub


Private Function xlFillArray(strWorkbook As String, _
                             strRange As String) As Variant
'Graham Mayor - http://www.gmayor.com - 24/09/2016
Dim RS As Object
Dim CN As Object
Dim iRows As Long

strRange = strRange & "$]"    'Use this to work with a named worksheet
    'strRange = strRange & "]" 'Use this to work with a named range
    Set CN = CreateObject("ADODB.Connection")

    'Set HDR=NO for no header row
    CN.Open ConnectionString:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
                              "Data Source=" & strWorkbook & ";" & _
                              "Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"""

    Set RS = CreateObject("ADODB.Recordset")
    RS.Open "SELECT * FROM [" & strRange, CN, 2, 1

    With RS
        .MoveLast
        iRows = .RecordCount
        .MoveFirst
    End With
    xlFillArray = RS.GetRows(iRows)
    If RS.State = 1 Then RS.Close
    Set RS = Nothing
    If CN.State = 1 Then CN.Close
    Set CN = Nothing
lbl_Exit:
    Exit Function
End Function
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote
  #3  
Old 02-23-2023, 03:54 AM
syl3786 syl3786 is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Advanced Beginner
How to export hyperlinks from Excel to Word?
 
Join Date: Jan 2023
Posts: 97
syl3786 is on a distinguished road
Default

Quote:
Originally Posted by gmayor View Post
Used in conjunction with Document Batch Processes the following custom process - AddHLinks - will add the links associated with the texts in your Worksheet.
Change the path of the workbook and the worksheet name as appropriate:
Code:
Option Explicit

Const strWorkbook As String = "E:\Path\Example.xlsx"        'The path of the workbook
Const strSheet As String = "Sheet1"        'The name of the worksheet

Sub AddHLinks(oDoc As Document)
Dim Arr() As Variant
Dim i As Long
Dim oRng As Range
Dim sFindText As String
Dim sReplaceText As String
    Arr = xlFillArray(strWorkbook, strSheet)
    For i = 0 To UBound(Arr, 2)
        sFindText = Arr(0, i)
        sReplaceText = Arr(1, i)
        Set oRng = oDoc.Range
        With oRng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            Do While .Execute(findText:=sFindText, _
                              MatchWholeWord:=True, _
                              Forward:=True, _
                              Wrap:=wdFindStop) = True
                oRng.Hyperlinks.Add oRng, sReplaceText
                oRng.End = oRng.End + 1
                oRng.Collapse wdCollapseEnd
                DoEvents
            Loop
        End With
    Next
lbl_Exit:
    Exit Sub
End Sub


Private Function xlFillArray(strWorkbook As String, _
                             strRange As String) As Variant
'Graham Mayor - http://www.gmayor.com - 24/09/2016
Dim RS As Object
Dim CN As Object
Dim iRows As Long

strRange = strRange & "$]"    'Use this to work with a named worksheet
    'strRange = strRange & "]" 'Use this to work with a named range
    Set CN = CreateObject("ADODB.Connection")

    'Set HDR=NO for no header row
    CN.Open ConnectionString:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
                              "Data Source=" & strWorkbook & ";" & _
                              "Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"""

    Set RS = CreateObject("ADODB.Recordset")
    RS.Open "SELECT * FROM [" & strRange, CN, 2, 1

    With RS
        .MoveLast
        iRows = .RecordCount
        .MoveFirst
    End With
    xlFillArray = RS.GetRows(iRows)
    If RS.State = 1 Then RS.Close
    Set RS = Nothing
    If CN.State = 1 Then CN.Close
    Set CN = Nothing
lbl_Exit:
    Exit Function
End Function
Thank you Gmayor! May I ask if I can just use the Macro but not install any add-ins? As I am not allowed to install any add-ins in company's computer.
Reply With Quote
  #4  
Old 02-23-2023, 04:39 AM
gmayor's Avatar
gmayor gmayor is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Expert
 
Join Date: Aug 2014
Posts: 4,137
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

The batch add-in automates the process on multiple documents, however you can run the code on one document by calling it from a macro e.g.
Code:
Sub Macro1()
AddHLinks ActiveDocument

End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote
  #5  
Old 02-23-2023, 04:44 AM
syl3786 syl3786 is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Advanced Beginner
How to export hyperlinks from Excel to Word?
 
Join Date: Jan 2023
Posts: 97
syl3786 is on a distinguished road
Default

Quote:
Originally Posted by gmayor View Post
The batch add-in automates the process on multiple documents, however you can run the code on one document by calling it from a macro e.g.
Code:
Sub Macro1()
AddHLinks ActiveDocument

End Sub
Thank you Gmayor! It works well! May I also ask if I can add input box for input the path?
Reply With Quote
  #6  
Old 02-23-2023, 08:05 AM
gmayor's Avatar
gmayor gmayor is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Expert
 
Join Date: Aug 2014
Posts: 4,137
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

I guess so - make changes as follows:


Code:
Option Explicit

Private strWorkbook As String
Private strSheet As String

Sub Macro1()
strWorkbook = BrowseForFile("Select Workbook", True)
strSheet = InputBox("Enter worksheet name", "Worksheet", "Sheet1")
AddHLinks ActiveDocument, strWorkbook, strSheet
End Sub

Sub AddHLinks(oDoc As Document, strWorkbook As String, strSheet As String)

'etc
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote
  #7  
Old 02-23-2023, 08:49 AM
syl3786 syl3786 is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Advanced Beginner
How to export hyperlinks from Excel to Word?
 
Join Date: Jan 2023
Posts: 97
syl3786 is on a distinguished road
Default

Quote:
Originally Posted by gmayor View Post
I guess so - make changes as follows:


Code:
Option Explicit

Private strWorkbook As String
Private strSheet As String

Sub Macro1()
strWorkbook = BrowseForFile("Select Workbook", True)
strSheet = InputBox("Enter worksheet name", "Worksheet", "Sheet1")
AddHLinks ActiveDocument, strWorkbook, strSheet
End Sub

Sub AddHLinks(oDoc As Document, strWorkbook As String, strSheet As String)

'etc
Thank you so much for your help! You are genius! I ran it but the system informed "BrowseForFile" has not defined. Then I added a function for the "BrowseForFile". It successfully add the hyperlinks to the texts.

[/CODE]

Private Function BrowseForFile(Optional strTitle As String, Optional bExcel As Boolean) As String
Dim fDialog As FileDialog
On Error GoTo err_Handler
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.Title = strTitle
.AllowMultiSelect = False
.Filters.Clear
If bExcel Then
.Filters.Add "Excel workbooks", "*.xls,*.xlsx,*.xlsm"
Else
.Filters.Add "Word documents", "*.doc,*.docx,*.docm"
End If
.InitialView = msoFileDialogViewList
If .Show <> -1 Then GoTo err_Handler:
BrowseForFile = fDialog.SelectedItems.Item(1)
End With
lbl_Exit:
Exit Function
err_Handler:
BrowseForFile = vbNullString
Resume lbl_Exit
End Function

[/CODE][/QUOTE]

But the system always pop out a message 94 (Invalid use of Null (Error 94)) after it ran.

The code highlighted: sFindText = Arr(0, i)

(Invalid use of Null (Error 94) | Microsoft Learn)

May I know how to avoid or ignore it? I guess the problem comes from the Excel Sheet. Since the first column of my excel file is a 6-digit number like " '001234", which started from the symbol " ' ". Without " ' ", the 6-digit number will become a 4-digit number.

Last edited by syl3786; 02-23-2023 at 05:08 PM.
Reply With Quote
  #8  
Old 02-23-2023, 05:11 PM
syl3786 syl3786 is offline How to export hyperlinks from Excel to Word? Windows 10 How to export hyperlinks from Excel to Word? Office 2019
Advanced Beginner
How to export hyperlinks from Excel to Word?
 
Join Date: Jan 2023
Posts: 97
syl3786 is on a distinguished road
Default

Quote:
Originally Posted by syl3786 View Post
Thank you so much for your help! You are genius! I ran it but the system informed "BrowseForFile" has not defined. Then I added a function for the "BrowseForFile". It successfully add the hyperlinks to the texts.

[/CODE]

Private Function BrowseForFile(Optional strTitle As String, Optional bExcel As Boolean) As String
Dim fDialog As FileDialog
On Error GoTo err_Handler
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.Title = strTitle
.AllowMultiSelect = False
.Filters.Clear
If bExcel Then
.Filters.Add "Excel workbooks", "*.xls,*.xlsx,*.xlsm"
Else
.Filters.Add "Word documents", "*.doc,*.docx,*.docm"
End If
.InitialView = msoFileDialogViewList
If .Show <> -1 Then GoTo err_Handler:
BrowseForFile = fDialog.SelectedItems.Item(1)
End With
lbl_Exit:
Exit Function
err_Handler:
BrowseForFile = vbNullString
Resume lbl_Exit
End Function

[/CODE]

I put "On Error Resume Next" before the "Dim Arr() As Variant". Then Error 94 doesn't pop out.
Reply With Quote
Reply



Similar Threads
Thread Thread Starter Forum Replies Last Post
Export Word Data to Excel anifa Word 2 12-11-2022 02:51 PM
How to export hyperlinks from Excel to Word? Word form with the intent of Excel export Flyckten Word VBA 5 09-03-2018 05:34 AM
How to export hyperlinks from Excel to Word? VBA Export Data as Text from Excel to Word lwbarnes Word VBA 3 06-09-2016 02:47 PM
Through VBA, export range from Excel to Word duugg Word VBA 0 08-24-2009 07:50 PM
Word to Excel hyperlinks and spaces gak Word 1 09-14-2008 08:38 AM

Other Forums: Access Forums

All times are GMT -7. The time now is 09:06 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2025, vBulletin Solutions Inc.
Search Engine Optimisation provided by DragonByte SEO (Lite) - vBulletin Mods & Addons Copyright © 2025 DragonByte Technologies Ltd.
MSOfficeForums.com is not affiliated with Microsoft