Search code examples
excelvbaoutlookhtml-email

Change column width of Run de Bruin Outlook Mail


I'm using Ron de Bruins code to send a range by e-mail but I haven't figured out how to change the column width of the html range that is sent. I tried to add EntireRow.Autofit & EntireColumn.Autofit which works but I want some columns to be 15 of width precisely and not much. Thanks for your time & help!

Here is the code below:

Function rangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2013
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"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).Select
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    '.Cells(1).Select
    '.Cells(1).EntireRow.AutoFit works but i don't have specific width to choose
    '.Cells(1).EntireColumn.AutoFit
    '.Columns(1).ColumnWidth = 10.45 doesn't work
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
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

'Read all data from the htm file into RangetoHTML
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=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing

End Function

Solution

  • You can set the column width in your source range before calling the Function.

    Sub Set_Col_Width()
        ActiveWorkbook.ActiveSheet.Columns("B:B").ColumnWidth = 20
        ActiveWorkbook.ActiveSheet.Columns("D:D").ColumnWidth = 10
    End Sub
    

    The HTML generated by the function uses the width you set:

      <td class=xl154597 width=150 style='width:112pt'>Column B</td>
      <td class=xl154597 width=78 style='width:58pt'>Column D</td>