VBA for emailing sheet 1 of multiple workbooks from a directory that i can select

diabloxx

New Member
Joined
Jan 21, 2012
Messages
16
i am hoping i'm not breaking any protocol or ettiquette, i did post this on another site, my apologies if i am, but i have been working on this all day and can't figure this out, and i'm a bit desperate ;-)

I am new to VBA and am looking for some assistance.
i found a great tutorial from Ron DeBruin, for emailing as html in outlook. i was hoping someone could help me adapt the code i have to fit my needs.

What i am looking to do is this;
i have a folder that has 70+ workbooks, all of them named for a different region of the U.S.

i would like to change the code i am using to let me choose the folder with all my workbooks (it changes from month to month), take the first worksheet in each workbook and create individual emails in outlook for each workbook.

Ideally I'd like it to be able to associate the name of the workbook with a distribution group in outlook, but i'll settle with just having the email open and i'd type that in myself.

I'm using both office 2007 and 2010.

Thank you all in advance!

here's the code that i currently have working as of today:


Code:
    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
         ' Build the string that you want to add.
        
        ' Delete the htm file.
        Kill TempFile
     
        Set ts = Nothing
        Set fso = Nothing
        Set TempWB = Nothing
        Dim StrBody As String
    
    
    End Function
    Sub Jims_Mail_Sheet_Outlook_Body()
    ' You need to use this module with the RangetoHTML subroutine.
    ' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010, Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, and Outlook 2010.
        Dim rng As Range
        Dim OutApp As Object
        Dim OutMail As Object
        With Application
            .EnableEvents = False
            .ScreenUpdating = False
        End With
     Dim StrBody As String
    ' Build the string that you want to add.
    StrBody = "Here is this months Idle 180 days product report for your region" & "<br>" & _
              "This is line 2" & "<br>" & _
              "This is line 3" & "<br><br><br>"
        Set rng = Nothing
        Set rng = ActiveSheet.UsedRange
        ' You can also use a sheet name here.
        'Set rng = Sheets("YourSheet").UsedRange
    
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)
     
        On Error Resume Next
        With OutMail
            .To = ""
            .CC = ""
            .BCC = ""
            .Subject = "Idle 180 Days Report - " & Worksheets("sheet1").Range("k21")
            .HTMLBody = StrBody & RangetoHTML(rng)
                ' In place of the following statement, you can use ".Display" to
                ' display the e-mail message.
            .Display
        End With
        On Error GoTo 0
     
        With Application
            .EnableEvents = True
            .ScreenUpdating = True
        End With
     
        Set OutMail = Nothing
        Set OutApp = Nothing
    End Sub
 

Excel Facts

Whats the difference between CONCAT and CONCATENATE?
The newer CONCAT function can reference a range of cells. =CONCATENATE(A1,A2,A3,A4,A5) becomes =CONCAT(A1:A5)
Try...

Code:
[font=Courier New]    [color=darkblue]Sub[/color] Jims_Mail_Sheet_Outlook_Body()
    
        [color=darkblue]Dim[/color] OutApp [color=darkblue]As[/color] [color=darkblue]Object[/color]
        [color=darkblue]Dim[/color] OutMail [color=darkblue]As[/color] [color=darkblue]Object[/color]
        [color=darkblue]Dim[/color] wkbSource [color=darkblue]As[/color] Workbook
        [color=darkblue]Dim[/color] rng [color=darkblue]As[/color] Range
        [color=darkblue]Dim[/color] strMyFolder [color=darkblue]As[/color] [color=darkblue]String[/color]
        [color=darkblue]Dim[/color] strFile [color=darkblue]As[/color] [color=darkblue]String[/color]
        [color=darkblue]Dim[/color] strBody [color=darkblue]As[/color] [color=darkblue]String[/color]
        
        [color=darkblue]With[/color] Application.FileDialog(msoFileDialogFolderPicker)
            .Title = "Please select a folder..."
            .InitialFileName = Application.DefaultFilePath & "\" [color=green]'change the default folder accordingly[/color]
            .Show
            [color=darkblue]If[/color] .SelectedItems.Count > 0 [color=darkblue]Then[/color]
                strMyFolder = .SelectedItems(1) & "\"
            [color=darkblue]Else[/color]
                [color=darkblue]Exit[/color] [color=darkblue]Sub[/color]
            [color=darkblue]End[/color] [color=darkblue]If[/color]
        [color=darkblue]End[/color] [color=darkblue]With[/color]
        
        [color=darkblue]With[/color] Application
            .EnableEvents = [color=darkblue]False[/color]
            .ScreenUpdating = [color=darkblue]False[/color]
        [color=darkblue]End[/color] [color=darkblue]With[/color]
        
        [color=darkblue]Set[/color] OutApp = CreateObject("Outlook.Application")
        
        strBody = "Here is this months Idle 180 days product report for your region..."
        
        strFile = Dir(strMyFolder & "*.xlsx") [color=green]'change the file extension acccordingly[/color]
        
        [color=darkblue]Do[/color] [color=darkblue]While[/color] Len(strFile) > 0
        
            [color=darkblue]Set[/color] wkbSource = Workbooks.Open(strMyFolder & strFile)
        
            [color=darkblue]Set[/color] rng = wkbSource.Worksheets("Sheet1").UsedRange
        
            [color=darkblue]Set[/color] OutMail = OutApp.CreateItem(0)
         
            [color=darkblue]On[/color] [color=darkblue]Error[/color] [color=darkblue]Resume[/color] [color=darkblue]Next[/color]
            [color=darkblue]With[/color] OutMail
                .To = ""
                .CC = ""
                .BCC = ""
                .Subject = "Idle 180 Days Report - " & wkbSource.Worksheets("Sheet1").Range("K21")
                .HTMLBody = strBody & RangetoHTML(rng)
                .Display
                [color=green]'Send[/color]
            [color=darkblue]End[/color] [color=darkblue]With[/color]
            [color=darkblue]On[/color] [color=darkblue]Error[/color] [color=darkblue]GoTo[/color] 0
            
            wkbSource.Close savechanges:=[color=darkblue]False[/color]
            
            strFile = Dir
            
        [color=darkblue]Loop[/color]
     
        [color=darkblue]With[/color] Application
            .EnableEvents = [color=darkblue]True[/color]
            .ScreenUpdating = [color=darkblue]True[/color]
        [color=darkblue]End[/color] [color=darkblue]With[/color]
     
        [color=darkblue]Set[/color] OutMail = [color=darkblue]Nothing[/color]
        [color=darkblue]Set[/color] OutApp = [color=darkblue]Nothing[/color]
        
    [color=darkblue]End[/color] [color=darkblue]Sub[/color]
[/font]
 
Upvote 0
Dominec!!

This is Amazing!!

Thank you so much!

one more favor if i may be a pest, is there a way to add the users default signature into the body?

i'm going to have multiple users using this amazing macro, i'd like for them to not have to insert their outlook signatures into every one.

I am trying to understand Ron Debruins instructions but i can't get it to work even on my own machine.

Code:
SigString = "C:\Documents and Settings\" &  	Environ("username") & _
            "\Application  	Data\Microsoft\Signatures\Mysig.txt"

is this all the code i need? or am i missing a step?

Thanks again in advance!
 
Upvote 0
Dominec!!

This is Amazing!!

Thank you so much!

You're very welcome!

one more favor if i may be a pest, is there a way to add the users default signature into the body?

i'm going to have multiple users using this amazing macro, i'd like for them to not have to insert their outlook signatures into every one.

I am trying to understand Ron Debruins instructions but i can't get it to work even on my own machine.

Code:
SigString = "C:\Documents and Settings\" &  	Environ("username") & _
            "\Application  	Data\Microsoft\Signatures\Mysig.txt"

is this all the code i need? or am i missing a step?

Thanks again in advance!

First, make sure that you've set up a signature in Outlook, if you haven't already done so. Then, you'll need to replace Mysig.txt with the name of your signature file. And, actually, since you're using HTML, you should use the .htm file, instead of the .txt file. So you would use Mysig.htm (again, changing the filename accordingly). Here is the code, with the appropriate changes and additions in red. Note that it also includes code for the "GetBoiler" function.

Code:
    Sub Jims_Mail_Sheet_Outlook_Body()
    
        Dim OutApp As Object
        Dim OutMail As Object
        Dim wkbSource As Workbook
        Dim rng As Range
        Dim strMyFolder As String
        Dim strFile As String
        Dim strBody As String
        [COLOR="Red"]Dim SigString As String
        Dim Signature As String[/COLOR]
        
        With Application.FileDialog(msoFileDialogFolderPicker)
            .Title = "Please select a folder..."
            .InitialFileName = Application.DefaultFilePath & "\" 'change the default folder accordingly
            .Show
            If .SelectedItems.Count > 0 Then
                strMyFolder = .SelectedItems(1) & "\"
            Else
                Exit Sub
            End If
        End With
        
        With Application
            .EnableEvents = False
            .ScreenUpdating = False
        End With
        
        Set OutApp = CreateObject("Outlook.Application")
        
        strBody = "Here is this months Idle 180 days product report for your region..."
        
        [COLOR="Red"]SigString = "C:\Documents and Settings\" & Environ("username") & _
            "\Application Data\Microsoft\Signatures\Mysig.htm"[/COLOR] 'Change the filename for the signature accordingly
    
        [COLOR="Red"]If Dir(SigString) <> "" Then
            Signature = GetBoiler(SigString)
        Else
            Signature = ""
        End If[/COLOR]

        strFile = Dir(strMyFolder & "*.xlsx") 'change the file extension acccordingly
        
        Do While Len(strFile) > 0
        
            Set wkbSource = Workbooks.Open(strMyFolder & strFile)
        
            Set rng = wkbSource.Worksheets("Sheet1").UsedRange
        
            Set OutMail = OutApp.CreateItem(0)
         
            On Error Resume Next
            With OutMail
                .To = ""
                .CC = ""
                .BCC = ""
                .Subject = "Idle 180 Days Report - " & wkbSource.Worksheets("Sheet1").Range("K21")
                .HTMLBody = strBody & RangetoHTML(rng)[COLOR="Red"] & vbNewLine & vbNewLine & Signature[/COLOR]
                .Display
                'Send
            End With
            On Error GoTo 0
            
            wkbSource.Close savechanges:=False
            
            strFile = Dir
            
        Loop
     
        With Application
            .EnableEvents = True
            .ScreenUpdating = True
        End With
     
        Set OutMail = Nothing
        Set OutApp = Nothing
        
    End Sub
    
    [COLOR="Red"]Function GetBoiler(ByVal sFile As String) As String
        '**** Kusleika
        Dim fso As Object
        Dim ts As Object
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
        GetBoiler = ts.readall
        ts.Close
    End Function[/COLOR]

In case you're using Vista or Windows 7 as your operating system, you'll need to replace...

Code:
SigString = "C:\Documents and Settings\" & Environ("username") & _
            "\Application Data\Microsoft\Signatures\Mysig.htm"

with

Code:
SigString = "C:\Users\" & Environ("username") & _
     "\AppData\Roaming\Microsoft\Signatures\Mysig.htm"
 
Last edited:
Upvote 0
THANK YOU THANK YOU THANK YOU!!!!

You have been a godsend for me!

I'm trying to play around with your macro, I'm trying to alter it slightly for many other uses, how do i get it so that it does everything here, but instead of the range, it just sends the whole workbook as an attachment.
I can't imagine that much needs to change, or am i wrong?

So, essentially i still want it to loop through a selected directory and create emails for each workbook it finds, adding the workbook as an attachment.

i understand you're helping out probably a lot of users so it's cool if you don't have the time. you've been MORE than helpful to me already!

James
 
Upvote 0
Try...

Code:
    Sub Jims_Mail_Sheet_Outlook_Body()
    
        Dim OutApp As Object
        Dim OutMail As Object
        Dim strMyFolder As String
        Dim strFile As String
        Dim strBody As String
        Dim SigString As String
        Dim Signature As String
        
        With Application.FileDialog(msoFileDialogFolderPicker)
            .Title = "Please select a folder..."
            .InitialFileName = Application.DefaultFilePath & "\" 'change the default folder accordingly
            .Show
            If .SelectedItems.Count > 0 Then
                strMyFolder = .SelectedItems(1) & "\"
            Else
                Exit Sub
            End If
        End With
        
        With Application
            .EnableEvents = False
            .ScreenUpdating = False
        End With
        
        Set OutApp = CreateObject("Outlook.Application")
        
        strBody = "Here is this months Idle 180 days product report for your region..."
        
        SigString = "C:\Documents and Settings\" & Environ("username") & _
            "\Application Data\Microsoft\Signatures\Mysig[COLOR="Red"].txt[/COLOR]" 'Change the filename for the signature accordingly
    
        If Dir(SigString) <> "" Then
            Signature = GetBoiler(SigString)
        Else
            Signature = ""
        End If

        strFile = Dir(strMyFolder & "*.xlsx") 'change the file extension acccordingly
        
        Do While Len(strFile) > 0
        
            Set OutMail = OutApp.CreateItem(0)
         
            On Error Resume Next
            With OutMail
                .To = ""
                .CC = ""
                .BCC = ""
                [COLOR="Red"].Subject = "Idle 180 Days Report"[/COLOR]
                [COLOR="Red"].Body = strBody & vbNewLine & vbNewLine & Signature
                .Attachments.Add strMyFolder & strFile[/COLOR]
                .Display
                'Send
            End With
            On Error GoTo 0
            
            strFile = Dir
            
        Loop
     
        With Application
            .EnableEvents = True
            .ScreenUpdating = True
        End With
     
        Set OutMail = Nothing
        Set OutApp = Nothing
        
    End Sub

Notice that I changed the subject line to avoid having to open each workbook. Opening each workbook to retrieve the value in K21 would slow the macro down. However, if you'd prefer you can always change the code to do so. Also, make sure that you're using the correct SigString for your operating system.
 
Upvote 0
freaking awesome!!

just got to find out how to add the attachment name in the subject line and i'm good!

Thank you so very much!
 
Upvote 0
Try...

Code:
.Subject = "Idle 180 Days Report - " & strFile
 
Upvote 0
Domenic,

i cannot say how much i appreciate everything you've just done for me. This is perfect.

thanks again!

have a great day.

James
 
Upvote 0

Forum statistics

Threads
1,223,910
Messages
6,175,318
Members
452,634
Latest member
cpostell

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top