Question

J'ai donc rassemblé à différents endroits sur Internet un code pour exporter une table dans Outlook et l'envoyer automatiquement et je viens de remarquer que l'e-mail n'est pas vraiment convivial (principalement en raison du fait que le corps de messagerie est envoyé sous forme de HTML et non En tant que «texte riche», rappelez-vous que le tableau doit également être en format riche). Je manque une ligne de code qui indiquera à Outlook d'envoyer un e-mail comme "texte riche" mais je ne sais pas ce que c'est. Quelqu'un peut-il m'aider? Veuillez consulter le code complet ci-dessous (excuses pour le long du code à l'avance).

Merci p

Sub Mail_Sheet_Outlook_Body()
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set rng = Nothing
    Set rng = Selection.SpecialCells(xlCellTypeVisible)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = "email@email.com"
        .CC = ""
        .BCC = ""
        .Subject = "Enter Subject text here"
        .HTMLBody = RangetoHTML(rng)
       '.Attachments.Add ("c:\temp\" & ActiveSheet.Range("DateSerial").Value & ".pdf")
        .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010, Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, and Outlook 2010.
    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 workbook to receive the data.
    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

    ' Publish the sheet to an .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 the RangetoHTML subroutine.
    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.
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function
Était-ce utile?

La solution

Contexte pour répondre

L'objectif de la question était de pouvoir faire envoyer une table Excel dans un e-mail lisible sur un Blackberry. Il y avait un certain nombre de harengs rouges avant que la cause du problème ne soit identifiée comme PublishObjects d'Excel. Le problème aurait pu être le grand nombre de formats CSS inutiles ou le dimensionnement des cellules et des polices en points, mais, quel que soit le problème, le HTML n'a pas pu être rendu correctement par le moteur d'affichage de BlackBerry.

J'ai créé un morceau de code VBA assez simple pour créer une table HTML à partir d'une gamme. Il a copié les valeurs, audacieuse, en italique, couleur de police, couleur d'arrière-plan et largeurs de colonne d'Excel à la table HTML. Bien que la première version ne réponde pas aux exigences complètes de Macutan, elle a démontré que l'approche était viable: un tableau HTML / CSS avec un minimum de formatage était affiché correctement et attrayant sur une mûre.

Alors que j'ai apporté de nouvelles améliorations pour répondre aux exigences du Macutan, j'ai découvert que le même problème existait avec d'autres téléphones intelligents et il y avait un besoin général d'une telle routine. Je continue à développer la routine avec l'intention que la version finale copie tous les formations Excel à la table HTML.

Le code ainsi que les instructions ont rapidement dépassé la limite de pile de pile de 30 000 caractères. J'ai passé de nouvelles versions à Macutan par e-mail. La documentation du module de code est ci-dessous. Si vous regardez mon profil, il y a une adresse e-mail. Je transmettrai des copies de mon code sur demande.

  ' Converts a rectangular range within an Excel worksheet to an Html document.

  ' RangeToHtml is the only routine in this module designed to be called from
  ' outside the module.  A typical call might be:
  '     Call RangeToHtml(Worksheets("Data"), 1, 1, RowBottom, ColRight, _
  '                                     BorderStyle=Separate, CellPadding=.25)

  ' The parameters of RangeToHtml are:
  '  * Wsht         A worksheet within an open workbook
  '  * RowTop       \
  '  * ColumnLeft   | Together these specify a rectangular range within
  '  * RowBottom    | Wsht.  This is the range to be converted to Html.
  '  * ColumnRight  /
  '  * Options      Zero or more strings of the form OptionName=OptionValue
  '                 specifying which, if any, of the available high-level,
  '                 formatting options are required.

  ' Individual options are checked.  "OptionName" must be the name of a documented
  ' option and "OptionValue" must be a permitted value for that option. No space is
  ' permitted before or after the equals sign. OptionNames and OptionValues are
  ' case insensitive; that is "BorderStyle=Collapse" and "borderstyle=collapse" are
  ' both acceptable and have the same meaning. However, options are not tested for
  ' duplicates. You can, for example, specify:
  '     "BorderStyle=Separate", "BorderStyle=Collapse".
  ' In this example, "BorderStyle=Separate" will overwrite the default collapse style
  ' and then "BorderStyle=Collapse" will overwrite "BorderStyle=Separate"

  ' The available options are:
  '   * BorderStyle=Collapse
  '   * BorderStyle=Separate
  '       With Html/Css, the cells of a table can touch so there appears to be a single
  '       border between adjacent cells or they can be separated by a small gap so it is
  '       obvious that each cell has its own border. If no BorderStyle is specified,
  '       "BorderStyle=Collapse" is the default which means cell borders touch.
  '   * CellPad=.nn
  '       If this option is omitted or if "CellPad=0" is specified, there is a minimal gap
  '       between the cell border and its contents. If the option is, for example,
  '       "CellPad=.25" then will be a gap of .25 ems around the cell contents. An "em" is
  '       a measure of length equal to the height of the cell's font.
  '   * TableWidth=nnn
  '       If this option is omitted or if "TableWidth=100" is specified, the table occupies
  '       the entire available display width.  If the option is, for example, "TableWidth=50",
  '       the table will occupy 50% of the available display width. "nnn" can be greater than
  '       100 if you wish the user to scroll to see the entire table.

  ' The table below lists the formats handled at cell and or in-cell level. The default value
  ' column is explained below.
  '   CELL-LEVEL            IN-CELL           DEFAULT VALUE
  '   bold                  bold              false
  '   italic                italic            false
  '   strikethrough         strikethrough     false
  '   underline single      underline single  no underline
  '   underline double      underline double  no underline
  '   underline accounting                    no underline
  '   font colour           font colour       black
  '   background colour                       white
  '   horizontal alignment                    left for string; right for numbers and dates
  '   font size             font size         11 or as set as the Excel application level
  '   font name             font name         Calibri or as set as the Excel application level
  '   vertical alignment                      bottom

  ' There is no Html/Css equivalent to double or accouting underlining so both are
  ' converted to single underline.

  ' Each format is checked for every cell within the range. Formatting information is only
  ' output to the Html/Css if a format has a non-default value so the output is as clean and
  ' crisp as possible. You need to be careful about font name and size. Many change the name
  ' and size for a worksheet but the routine has no access to the worksheet's standard name
  ' and size; it is the Excel standard that determines the default.

  ' Html/Css does not handle wrap text at the cell level.  If no Excel cell has wrap text set
  ' then the routine does not output any column size information and columns widths are
  ' entirely determined by the receiver's browser.  If any cell has wrap text set then column
  ' widths are set by percentage so their relationship depends on the Excel column widths.

  ' Excel borders are not checked so any borders within the worksheet will not be converted.
  ' Instead every cell is given a thin, grey border so ther Html looks like a default
  ' Excel worksheet.

  ' If the cell value is numeric, the number format is checked for colour names. If
  ' appropriate, the colour specified in the number format will overwrite the cell's font
  ' colour.  See UpdateHtmlFontColourForNumericFormat for more information.

  ' Excel's default vertical alignment is "bottom" but Html/Css's is "center". If a cell
  ' is a single line, the difference will not be apparent but the Html/Css will be bigger
  ' than necessary because of "vertical-align:bottom" for every cell. It may be worth
  ' setting every cell's vertical alignment to "center".

  ' Merged cells are converted to the Html equivalent.

  ' Most of the work is performed by the macro HtmlStyleTable. This routine returns two
  ' strings, Style and Table, which RangeToHtml wraps in an Html envelope to create the
  ' document returned as a string to the caller.  Style and Table will look like:

  ' Style:
  '      table {border-collapse:collapse;}
  '      td {border-style:solid; border-width:1px; border-color:#BFBFBF;}
  '      td.backclr-0000FF {background-color:#0000FF;}
  '      td.backclr-D7EAF4 {background-color:#D7EAF4;}
  '         :   :   :
  '      span.bold {font-weight:bold;}
  '      span.fontclr-0070C0 {color:#0070C0;}
  '    The first two entries in Style are fixed . All other entries depend on
  '    the formats that appear in the worksheets. The td.xxx entries are used for
  '    cell-level formats. The span.xxx entries are used for in-cell formats.
  '    "In-cell formats" refers to part of a cell value being, for example, bold
  '    and part being non-bold.
  ' Table:
  '     <table class="bord-collapse">
  '       <tr>
  '         <td rowspan=2 style="width:29.41%" class="back-D7F4EA bold hAlign-center fontsize-095 fontname-Arial">Product</td>
  '         <td rowspan=2 style="width:11.76%" class="back-D7F4EA bold hAlign-center fontsize-095 fontname-Arial">Position</td>

  '   Mar12  I coded something similar in response to a Stack Overflow question. The main
  '          difference is that with the earlier version the formatting styles (for example:
  '          "background-color:#D7EAF4;") were all within the individual TD elements' STYLE
  '          attribute. I believe having all the styles in a STYLE element and references
  '          them by name in the TD elements gives a cleaner document.
  '   ?????  Having answered the Stack Overflow question to the satisfaction of the OP, I
  '          continued developing the routine. It quickly became clear that a full
  '          conversion was not practical in VBA so I converted my code to VB before
  '          continuing. I have quite an attractive VB version but it is slower than I would
  '          like. There are many complaints on the internet about the speed of access to
  '          Excel from VB and some bizarre solutions. I discovered a different approach
  '          which meant a program could obtain a lot of information about a worksheet in a
  '          single call to the InterOp. That information was provided as a string for which
  '          the documentation was poor and often wrong. However, I did manage to decode the
  '          string. Sometime, I must bring all my separate routines together in a single
  '          program to give a fast, complete conversion.
  '   Jun16  A request for a copy of my original code meant I searched my archives for that
  '          code. I did not find that code but I realised I could write a better routine.
  '          All routines in this module were coded and debugged in stages. The first
  '          version handled three cell-level formats. The final version handled more
  '          formats at both cell and in-cell level.
  '   Aug16  Added HtmlStyleTable options.

Autres conseils

À l'intérieur de votre bloc avec un bloc, définissez le BodyFormat Propriété olFormatRichText.

With OutMail
.BodyFormat = olFormatRichText
' rest of your code

Faites-nous savoir si cela fonctionne.

Éditer:

Définition du HTMLBody La propriété convertira l'e-mail en HTML. Si vous définissez le BodyFormat Propriété olFormatRichText alors vous auriez besoin d'utiliser le Body Propriété, qui éliminerait la possibilité d'utiliser HTML.

Je ne vois donc aucune façon de configurer l'e-mail avec une table HTML et Envoyez-le comme un format de texte riche.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top