Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sub ConvertURLsToHyperlinks()
- '
- ' ConvertURLsToHyperlinks Macro
- ' Converts all complete URLs in the document to clickable hyperlinks
- '
- Dim doc As Document
- Dim para As Paragraph
- Dim rng As Range
- Dim text As String
- Dim processedCount As Integer
- Dim urlStart As Long
- Dim urlEnd As Long
- Dim urlText As String
- Dim hyperlinkAddress As String
- Dim i As Long
- ' Initialize
- Set doc = ActiveDocument
- processedCount = 0
- ' Turn off screen updating for better performance
- Application.ScreenUpdating = False
- ' Process each paragraph to find URLs
- For Each para In doc.Paragraphs
- Set rng = para.Range
- text = rng.text
- ' Find all URLs in this paragraph
- i = 1
- Do While i <= Len(text)
- urlStart = 0
- urlEnd = 0
- ' Look for different URL patterns
- If Mid(text, i, 8) = "https://" Then
- urlStart = i
- urlEnd = FindURLEnd(text, i + 8)
- ElseIf Mid(text, i, 7) = "http://" Then
- urlStart = i
- urlEnd = FindURLEnd(text, i + 7)
- ElseIf Mid(text, i, 6) = "ftp://" Then
- urlStart = i
- urlEnd = FindURLEnd(text, i + 6)
- ElseIf Mid(text, i, 4) = "www." Then
- urlStart = i
- urlEnd = FindURLEnd(text, i + 4)
- End If
- ' If we found a URL, convert it
- If urlStart > 0 And urlEnd > urlStart Then
- urlText = Mid(text, urlStart, urlEnd - urlStart + 1)
- ' Create range for this specific URL (include the last character)
- Set rng = doc.Range(para.Range.Start + urlStart - 1, para.Range.Start + urlEnd)
- ' Only create hyperlink if it's not already one
- If rng.Hyperlinks.Count = 0 Then
- ' Prepare hyperlink address
- If Left(urlText, 4) = "www." Then
- hyperlinkAddress = "http://" & urlText
- Else
- hyperlinkAddress = urlText
- End If
- ' Create the hyperlink
- doc.Hyperlinks.Add Anchor:=rng, Address:=hyperlinkAddress
- processedCount = processedCount + 1
- End If
- ' Move past this URL
- i = urlEnd + 1
- Else
- ' Move to next character
- i = i + 1
- End If
- Loop
- Next para
- ' Turn screen updating back on
- Application.ScreenUpdating = True
- ' Show completion message
- MsgBox "Conversion complete! " & processedCount & " URLs converted to hyperlinks.", vbInformation, "URL Conversion"
- End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement