Forum

Want to send a rang...
 
Notifications
Clear all

Want to send a range in a sheet with Outlook. But I want to give the user an option for attachment or copy

2 Posts
2 Users
0 Reactions
120 Views
(@promo1313)
Posts: 16
Eminent Member
Topic starter
 

Hi

 

I have a tool in which the user clicks a macro button and it send out the range of the sheet in the body of an email in Outlook.

 

We are having an issue that sometimes the range can be over 1000 rows long.  The receiver will have to copy paste it in a workbook anyways, so I wanted to give the sender the option with a MsgBox to select if they want the range sent as an attachment or in the body of the Outlook email

 

below is the code that I have:

 

Sub Main()
 
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim lastRow As Long
 
    Set rng = Nothing
    On Error Resume Next
 
    lastRow = Sheets("Sheet1").Columns(1).Find("*", , xlValues, , xlByRows, xlPrevious).Row
    Set rng = Sheets("Sheet1").Range("A1:F" & lastRow).SpecialCells(xlCellTypeVisible)
 
    
    On Error GoTo 0
 
    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If
 
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With
 
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
 
    On Error Resume Next
    With OutMail
        .To = Sheets("Contacts").Range("F4").Value
        .BCC = ""
        .Subject = "Expeditors Statement"
        .HTMLBody = RangetoHTML(rng)
        .Display 
    End With
    On Error GoTo 0
 
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
 
    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
 
 
Posted : 21/02/2020 4:53 pm
(@catalinb)
Posts: 1937
Member Admin
 

Hi Robert,

You can replace the line

.HTMLBody = RangetoHTML(Rng)

with:

If MsgBox("Send as attachment?", vbYesNo, "Sending Data") = vbYes Then
.Attachments.Add RangeToNewBook(Rng)
Else
.HTMLBody = RangetoHTML(Rng)
End If

And here is the function that creates the new book:

Function RangeToNewBook(ByVal Rng As Range) As String
Dim Wb As Workbook
Set Wb = Workbooks.Add
Rng.Copy Destination:=Wb.Worksheets(1).Cells(1)
Wb.SaveAs ThisWorkbook.Path & Application.PathSeparator & "Temp " & Format(Now(), "yyyymmddhhmmss") & ".xlsx"
RangeToNewBook = Wb.FullName
Wb.Close True
End Function

 
Posted : 25/02/2020 12:15 am
Share: