Thursday, 12 December 2013

VBA Macro: Embed a table in the Lotus notes mail body and send mail

This code is a combination codes picked from different websites

Option Explicit

Sub Send_Row_Or_Rows_1()
' Don't forget to copy the function RangetoHTML in the module.
' Working in Office 2000-2010
    Dim OutApp As Object
    Dim Maildb As Object
    Dim Session As Object
    Dim MailDbName As String
    Dim UserName As String
    Dim OutMail As Object
    Dim rng As Range
    Dim Ash As Worksheet
    Dim Cws As Worksheet
    Dim Rcount As Long
    Dim Rnum As Long
    Dim FilterRange As Range
    Dim FieldNum As Integer
    Dim mailAddress As String
    Dim ccmailAddress As String
    Dim StrBody As String
    Dim StrBody1 As String
    Dim NRTItemBody As Object
    Dim body As Object
    Dim stream As Object

    On Error GoTo cleanup
    Set Session = CreateObject("Notes.NotesSession")
        UserName = Session.UserName
    MailDbName = Left$(UserName, 1) & Right$(UserName, (Len(UserName) - InStr(1, UserName, " "))) & ".nsf"
        Set Maildb = Session.GETDATABASE("", MailDbName)
    If Maildb.IsOpen = True Then
          'Already open for mail
     End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

        Set Ash = ActiveSheet
StrBody = "Dear Sir " & "
" & _
              "Text" & "
" & _
              "Text" & "
    StrBody1 = "
" & _
    "Text" & "
" & _
       "Text" & "
    'Set filter range and filter column (Column with names)
    Set FilterRange = Ash.Range("A1:P" & Ash.Rows.Count)
    FieldNum = 1    'Filter column = A because the filter range start in A

    'Add a worksheet for the unique list and copy the unique list in A1
    Set Cws = Worksheets.Add
    FilterRange.Columns(FieldNum).AdvancedFilter _
            Action:=xlFilterCopy, _
            CopyToRange:=Cws.Range("A1"), _
            CriteriaRange:="", Unique:=True

    'Count of the unique values + the header cell
    Rcount = Application.WorksheetFunction.CountA(Cws.Columns(1))

    'If there are unique values start the loop
    If Rcount >= 2 Then
        For Rnum = 2 To Rcount

            'Filter the FilterRange on the FieldNum column
            FilterRange.AutoFilter Field:=FieldNum, _
                                   Criteria1:=Cws.Cells(Rnum, 1).Value

            'Look for the mail address in the MailInfo worksheet
            mailAddress = ""
            ccmailAddress = ""
            On Error Resume Next
            mailAddress = Application.WorksheetFunction. _
                          VLookup(Cws.Cells(Rnum, 1).Value, _
                                Worksheets("Mailinfo").Range("A1:B" & _
                                Worksheets("Mailinfo").Rows.Count), 2, False)
            ccmailAddress = Application.WorksheetFunction. _
                          VLookup(Cws.Cells(Rnum, 1).Value, _
                                Worksheets("Mailinfo").Range("A1:C" & _
                                Worksheets("Mailinfo").Rows.Count), 3, False)
            On Error GoTo 0

            If mailAddress <> "" Then
                With Ash.AutoFilter.Range
                    On Error Resume Next
                    Set rng = .SpecialCells(xlCellTypeVisible)
                    On Error GoTo 0
                End With

               Set OutMail = Maildb.CREATEDOCUMENT
                On Error Resume Next
                OutMail.Form = "Memo"
                OutMail.sendto = mailAddress
                OutMail.CopyTo = ccmailAddress
                OutMail.Subject = "Action Items List"
                Set stream = Session.CreateStream
                Set body = OutMail.CreateMIMEEntity
                Call stream.WriteText(StrBody & RangetoHTML(rng) & StrBody1)
                Call body.SetContentFromText(stream, "text/html;charset=iso-8859-1", ENC_IDENTITY_7BIT)
                OutMail.SAVEMESSAGEONSEND = True
                OutMail.PostedDate = Now() 'Gets the mail to appear in the sent items folder
                OutMail.SEND 0, mailAddress

                              On Error GoTo 0
                Set OutMail = Nothing
            End If

            'Close AutoFilter
            Ash.AutoFilterMode = False

        Next Rnum
    End If

    Set Session = Nothing
    Application.DisplayAlerts = False
    Application.DisplayAlerts = True

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub
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"
    'Copy the range and create a new workbook to past the data in
    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
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        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, _
        .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
    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


No comments: