excelvbaoutlookhyperlinkhtml-email

Include hyperlinks in Excel range in html email


I found this code elsewhere.

Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
    
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With
    
    With TempWB.PublishObjects.Add( _
      SourceType:=xlSourceRange, _
      Filename:=TempFile, _
      Sheet:=TempWB.Sheets(1).Name, _
      Source:=TempWB.Sheets(1).UsedRange.Address, _
      HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")
    
    TempWB.Close savechanges:=False
    
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

This is called by a macro and puts an Excel range into an email. The range has a table and one of the columns includes hyperlinks.

The hyperlinks just send as blue underlined normal text.

I tried changing HtmlType:=xlHtmlStatic to something other than Static, but this threw errors.


Solution

  • I use the following in my email macros, which does display links which do send to target:

    Private Function CopyRangeToHTML(ByVal n As Range)
        Dim fso As Object, ts As Object, temp As String
        Dim wbs As Workbook: Set wbs = n.Worksheet.Parent
        temp = Environ$("temp") & "/" & Format(Now, "yyyyMMddHHmmss") & ".htm"
        With wbs.PublishObjects.Add(SourceType:=xlSourceRange, Filename:=temp, Sheet:=n.Worksheet.Name, Source:=n.Address, HtmlType:=xlHtmlStatic)
            .Publish (True)
        End With
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set ts = fso.GetFile(temp).OpenAsTextStream(1, -2)
        CopyRangeToHTML = ts.ReadAll
        ts.Close
        Kill temp
        Set ts = Nothing
        Set fso = Nothing
        Set wbs = Nothing
    End Function
    

    This looks extremely close to what you've got (de Bruin I think is the fellow's name), but was modified to include conditional formatting.

    One caveat to this is using a Teams based spreadsheet... the links are truncated and have that ".../" at the start, which are not selectable even when running these macros.