Home > database >  How to send mail in outlook with vba in excel
How to send mail in outlook with vba in excel

Time:04-14

I have a excel sheet with personal information such as name, email address etc. and I also have a VBA code that when a cell in a specific range is selected (range R in this case) then call the VBA macro to send a mail.

But how do I assign the email address of the specific person to my VBA code?

For example: if I click on cell R5, then the VBA macro should start running to send a mail to the email address in cell M5 and cell O5 or if I click on cell R10, then it should email to the email address in cell M10 and cell O10.

See below the code I have so far:

When I click on any cell in range R, the following VBA macro is triggered

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("R6:R1000000")) Is Nothing Then
        
        Call Send_Email

        End If
    End If
End Sub

The macro Send_Email:

Sub Send_Email()

Dim EmailApp As Outlook.Application

Dim NewEmailItem As Outlook.MailItem

Dim Scr As String

Set EmailApp = New Outlook.Application

Set NewEmailItem = EmailApp.CreateItem(olMailItem)

NewEmailItem.To = ****** here should be the cell reference ******

'NewEmailItem.CC = ****** here should be the cell reference ****** 

NewEmailItem.Subject = "abcd"

With NewEmailItem

.HTMLBody = "Hello abcd" etc. 

End With

End Sub

CodePudding user response:

Here is the sample code which does exactly the same - shows how to send an email to a list of recipients based on data stored in a workbook. The recipient email addresses must be in column A, and the body text of the email must be in the first text box on the active sheet:

Sub Sample()
   'Setting up the Excel variables.
   Dim olApp As Object
   Dim olMailItm As Object
   Dim iCounter As Integer
   Dim Dest As Variant
   Dim SDest As String
   
   'Create the Outlook application and the empty email.
   Set olApp = CreateObject("Outlook.Application")
   Set olMailItm = olApp.CreateItem(0)
   
   'Using the email, add multiple recipients, using a list of addresses in column A.
   With olMailItm
       SDest = ""
       For iCounter = 1 To WorksheetFunction.CountA(Columns(1))
           If SDest = "" Then
               SDest = Cells(iCounter, 1).Value
           Else
               SDest = SDest & ";" & Cells(iCounter, 1).Value
           End If
       Next iCounter
       
    'Do additional formatting on the BCC and Subject lines, add the body text from the spreadsheet, and send.
       .BCC = SDest
       .Subject = "FYI"
       .Body = ActiveSheet.TextBoxes(1).Text
       .Send
   End With
   
   'Clean up the Outlook application.
   Set olMailItm = Nothing
   Set olApp = Nothing
End Sub

In your scenario with a separate function for sending emails you can pass the required data via parameters.

  • Related