Advertisement
Guest User

Untitled

a guest
Jul 9th, 2025
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.93 KB | None | 0 0
  1. Sub ConvertURLsToHyperlinks()
  2. '
  3. ' ConvertURLsToHyperlinks Macro
  4. ' Converts all complete URLs in the document to clickable hyperlinks
  5. '
  6.  
  7. Dim doc As Document
  8. Dim para As Paragraph
  9. Dim rng As Range
  10. Dim text As String
  11. Dim processedCount As Integer
  12. Dim urlStart As Long
  13. Dim urlEnd As Long
  14. Dim urlText As String
  15. Dim hyperlinkAddress As String
  16. Dim i As Long
  17.  
  18. ' Initialize
  19. Set doc = ActiveDocument
  20. processedCount = 0
  21.  
  22. ' Turn off screen updating for better performance
  23. Application.ScreenUpdating = False
  24.  
  25. ' Process each paragraph to find URLs
  26. For Each para In doc.Paragraphs
  27. Set rng = para.Range
  28. text = rng.text
  29.  
  30. ' Find all URLs in this paragraph
  31. i = 1
  32. Do While i <= Len(text)
  33. urlStart = 0
  34. urlEnd = 0
  35.  
  36. ' Look for different URL patterns
  37. If Mid(text, i, 8) = "https://" Then
  38. urlStart = i
  39. urlEnd = FindURLEnd(text, i + 8)
  40. ElseIf Mid(text, i, 7) = "http://" Then
  41. urlStart = i
  42. urlEnd = FindURLEnd(text, i + 7)
  43. ElseIf Mid(text, i, 6) = "ftp://" Then
  44. urlStart = i
  45. urlEnd = FindURLEnd(text, i + 6)
  46. ElseIf Mid(text, i, 4) = "www." Then
  47. urlStart = i
  48. urlEnd = FindURLEnd(text, i + 4)
  49. End If
  50.  
  51. ' If we found a URL, convert it
  52. If urlStart > 0 And urlEnd > urlStart Then
  53. urlText = Mid(text, urlStart, urlEnd - urlStart + 1)
  54.  
  55. ' Create range for this specific URL (include the last character)
  56. Set rng = doc.Range(para.Range.Start + urlStart - 1, para.Range.Start + urlEnd)
  57.  
  58. ' Only create hyperlink if it's not already one
  59. If rng.Hyperlinks.Count = 0 Then
  60. ' Prepare hyperlink address
  61. If Left(urlText, 4) = "www." Then
  62. hyperlinkAddress = "http://" & urlText
  63. Else
  64. hyperlinkAddress = urlText
  65. End If
  66.  
  67. ' Create the hyperlink
  68. doc.Hyperlinks.Add Anchor:=rng, Address:=hyperlinkAddress
  69. processedCount = processedCount + 1
  70. End If
  71.  
  72. ' Move past this URL
  73. i = urlEnd + 1
  74. Else
  75. ' Move to next character
  76. i = i + 1
  77. End If
  78. Loop
  79. Next para
  80.  
  81. ' Turn screen updating back on
  82. Application.ScreenUpdating = True
  83.  
  84. ' Show completion message
  85. MsgBox "Conversion complete! " & processedCount & " URLs converted to hyperlinks.", vbInformation, "URL Conversion"
  86.  
  87. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement