Note: The other languages of the website are Google-translated. Back to English
Войти  \/ 
x
or
x
Регистрация  \/ 
x

or

Как отправить электронное письмо, если в Excel нажата кнопка?

Предположим, вам нужно отправить электронную почту через Outlook, нажав кнопку на листе Excel, как вы можете это сделать? В этой статье будет подробно представлен метод VBA для достижения этой цели.

Отправить электронное письмо, если нажата кнопка с кодом VBA


Отправить электронное письмо, если нажата кнопка с кодом VBA

Пожалуйста, сделайте следующее, чтобы отправить электронное письмо через Outlook, если в книге Excel нажата кнопка Command.

1. Вставьте командную кнопку на лист, нажав разработчик > Вставить > Командная кнопка (элемент управления ActiveX). Смотрите скриншот:

2. Щелкните вставленную кнопку управления правой кнопкой мыши, затем щелкните Просмотреть код из контекстного меню, как показано ниже.

3. В дебюте Microsoft Visual Basic для приложений В окне кода замените исходный код в окне кода следующим сценарием VBA.

Код VBA: отправить электронное письмо, если в Excel нажата кнопка

Private Sub CommandButton1_Click()
'Updated by Extendoffice 2017/9/14
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    On Error Resume Next
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Body content" & vbNewLine & vbNewLine & _
              "This is line 1" & vbNewLine & _
              "This is line 2"
                  On Error Resume Next
    With xOutMail
        .To = "Email Address"
        .CC = ""
        .BCC = ""
        .Subject = "Test email send by button clicking"
        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub

Заметки:

1). Измените текст сообщения электронной почты, как вам нужно, в xMailBody строка в коде.

2). Заменить Ваш e-mail с адресом электронной почты получателя в строке .To = "Адрес электронной почты".

3). Укажите получателей Cc и Bcc по мере необходимости в .CC = "" и .Bcc = "" разделов.

4). Измените тему электронного письма в строке .Subject = "Тестовое письмо, отправленное нажатием кнопки".

4. нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно.

5. Выключите режим дизайна, нажав разработчик > Режим проектирования. Смотрите скриншот:

С этого момента каждый раз, когда вы нажимаете на кнопку Command, автоматически создается электронное письмо с указанными получателями, темой и телом. Отправьте электронное письмо, нажав кнопку Отправить кнопку.

Внимание: Код VBA работает только при использовании Outlook в качестве почтовой программы.

С легкостью отправляйте электронную почту через Outlook на основе полей созданного списка рассылки в Excel:

Была основана Отправить письма полезности Kutools for Excel помогает отправлять электронную почту через Outlook на основе полей созданного списка рассылки в Excel.
Скачайте и попробуйте прямо сейчас! (30-дневная бесплатная трасса)


Статьи по теме:


Лучшие инструменты для работы в офисе

Kutools for Excel решает большинство ваших проблем и увеличивает вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма ...
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон...
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы... Предотвращение дублирования ячеек; Сравнить диапазоны...
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор ...
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое ...
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии...
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом ...
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF...
  • Более 300 мощных функций. Поддерживает Office / Excel 2007-2019 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
вкладка kte 201905

Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
офисный дно
Say something here...
symbols left.
You are guest
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Kevin · 2 months ago
    This works great for me, thank you. I'm having one challenge. I'd like to insert a hyperlink into the body of the email that says something like click "here" but currently can only get it to work using the full web address inserted into the body.
  • To post as a guest, your comment is unpublished.
    Leona · 4 months ago
    Hi, Thank you so much for this! Is there a way to have a conditional option to send an e-mail CC? For instance if a cell has a value in it, it adds a specific email to the CC in the command?
    Thanks!
  • To post as a guest, your comment is unpublished.
    Fahad · 7 months ago

    Private Sub CommandButton1_Click() 'Updated by Extendoffice 2017/9/14 Dim xOutApp As Object Dim xOutMail As Object Dim xMailBody As String On Error Resume Next Set xOutApp = CreateObject("Outlook.Application") Set xOutMail = xOutApp.CreateItem(0) xMailBody = "Body content" & vbNewLine & vbNewLine & _ "This is line 1" & vbNewLine & _ "This is line 2" On Error Resume Next With xOutMail .To = "???@???.com;???@???.com" .CC = "???@???.com;???@???.com" .BCC = "" .Subject = "Test email send by button clicking" .Body = xMailBody .Display 'or use .Send End With On Error GoTo 0 Set xOutMail = Nothing Set xOutApp = Nothing ActiveWorkbook.Close End Sub

  • To post as a guest, your comment is unpublished.
    Paiea · 8 months ago
    Hello, using the following VBA code and it works great! Thanks!

    I do need help with another spreadsheet that I have. I would like to have specific cell ranges as a snapshot in the body of the email and remove the spreadsheet attachment. Thank you for your assistance!

    Private Sub CommandButton1_Click()
    'Updated by Extendoffice 2017/9/14
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    On Error Resume Next
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    ActiveWorkbook.Save
    xMailBody = "xxxx" & vbNewLine & vbNewLine & _
    "xxxx" & vbNewLine & _
    "xxxx"
    On Error Resume Next
    With xOutMail
    .To = " xxxxxx "
    .CC = ""
    .BCC = ""
    .Subject = "xxxxx" & Date
    .Body = xMailBody
    .Attachments.Add ActiveWorkbook.FullName
    .Display 'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
    End Sub
  • To post as a guest, your comment is unpublished.
    Pai · 8 months ago
    Thank you for these codes.

    I need help with sending cell ranges as a snap shot in the body of the email instead of the excel attachment. Thank you for your help
  • To post as a guest, your comment is unpublished.
    Luke · 11 months ago
    Hello, can i make a vba function for checking due date in a table by clicking a button and send it thru Outlook when the due date is near about 3 months for each person, Thanks.
  • To post as a guest, your comment is unpublished.
    patrick.jackson · 1 years ago
    Hello, I am trying to have this send an email with attachment anytime someone selects Email. I keep getting an error and the debug is saying .AddAttachment Att is an issue? What am i missing?

    Dim iMsg As Object
    Dim iConf As Object
    Dim Flds As Variant
    Dim sht As Worksheet
    Dim CashierName As String
    Dim CashierTill As String
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim Att As String

    CashierName = Range("j4")
    CashierTill = Range("f4")

    TempFilePath = Environ$("temp") & "\"
    TempFileName = ActiveWorkbook.Name
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs TempFilePath & TempFileName
    ActiveWorkbook.SaveAs TempFilePath & "tempGolfCourseTill.xlsm"
    Att = TempFilePath & TempFileName
    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")

    iConf.Load -1
    Set Flds = iConf.Fields
    With Flds
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "xxxxxx@gmail.com"
    .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "xxxxxxxxx!"
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

    .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    .Update
    End With
    With iMsg
    Set .Configuration = iConf
    .To = "XXXXXXXX" 'sendToEmail
    .CC = ""
    .BCC = ""
    .From = "XXXXXX@gmail.com"
    .ReplyTo = "XXXXXXXX"
    .Subject = "XXXXXXXXXXXXXX & " " & Now
    .TextBody = "This is the Till balance per " & CashierName & "."
    .AddAttachment Att

    '.Send
    End With
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.DisplayAlerts = True
    End Sub
  • To post as a guest, your comment is unpublished.
    art · 1 years ago
    how to add hyperlink in the body together with this code?
  • To post as a guest, your comment is unpublished.
    Siddic · 1 years ago
    Hi Crystal,

    One more query, how to add code when i click command button for sending email then excel workbook window should also close?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Hi Siddic,
      Please separate multiple email addresses with semicolon. And if you need to close the workbook, the entire VBA is as below:

      Private Sub CommandButton1_Click()
      'Updated by Extendoffice 2017/9/14
      Dim xOutApp As Object
      Dim xOutMail As Object
      Dim xMailBody As String
      On Error Resume Next
      Set xOutApp = CreateObject("Outlook.Application")
      Set xOutMail = xOutApp.CreateItem(0)
      xMailBody = "Body content" & vbNewLine & vbNewLine & _
      "This is line 1" & vbNewLine & _
      "This is line 2"
      On Error Resume Next
      With xOutMail
      .To = "???@???.com;???@???.com"
      .CC = "???@???.com;???@???.com"
      .BCC = ""
      .Subject = "Test email send by button clicking"
      .Body = xMailBody
      .Display 'or use .Send
      End With
      On Error GoTo 0
      Set xOutMail = Nothing
      Set xOutApp = Nothing
      ActiveWorkbook.Close
      End Sub
  • To post as a guest, your comment is unpublished.
    Siddic · 1 years ago
    Hi Crystal,

    Could you please help how to add more email addresses in .TO and .CC?
    • To post as a guest, your comment is unpublished.
      King · 1 years ago
      Semi-Columns do the trick.
  • To post as a guest, your comment is unpublished.
    EXCELstruggles · 1 years ago
    Is it possible to have the button submit only the active worksheet as a non-editable form either excel or pdf format would be perfect? With the code I currently have (listed below) it attaches as a pdf but then wont open the file for the person that receives the email. Any help would be great



    Private Sub CommandButton1_Click()
    Dim xFile As String
    Dim xFormat As Long
    Dim Wb As Workbook
    Dim Wb2 As Workbook
    Dim FilePath As String
    Dim FileName As String
    Dim OutlookApp As Object
    Dim OutlookMail As Object
    On Error Resume Next
    Application.ScreenUpdating = False
    Set Wb = Application.ActiveWorkbook
    ActiveSheet.Copy
    Set Wb2 = Application.ActiveWorkbook
    Select Case Wb.FileFormat
    Case xlOpenXMLWorkbook:
    xFile = ".pdf"
    xFormat = xlOpenXMLWorkbook
    Case xlOpenXMLWorkbookMacroEnabled:
    If Wb2.HasVBProject Then
    xFile = ".pdf"
    xFormat = xlOpenXMLWorkbookMacroEnabled
    Else
    xFile = ".pdf"
    xFormat = xlOpenXMLWorkbook
    End If
    Case Excel8:
    xFile = ".pdf"
    xFormat = Excel8
    Case xlExcel12:
    xFile = ".pdf"
    xFormat = xlExcel12
    End Select
    FilePath = Environ$("temp") & "\"
    FileName = Wb.Name & Format(Now, "dd-mmm-yy h-mm-ss")
    Set OutlookApp = CreateObject("Outlook.Application")
    Set OutlookMail = OutlookApp.CreateItem(0)
    Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
    With OutlookMail
    .To = "test email"
    .CC = ""
    .BCC = ""
    .Subject = "supply request"
    .Body = "Please check and read this document."
    .Attachments.Add Wb2.FullName
    .Display
    '.Send
    End With
    Wb2.Close
    Kill FilePath & FileName & xFile
    Set OutlookMail = Nothing
    Set OutlookApp = Nothing
    End Sub



    • To post as a guest, your comment is unpublished.
      Excel issues · 1 years ago
      Did you manage to get an answer?
      • To post as a guest, your comment is unpublished.
        Erik · 7 months ago
        I haven't seen the solve... any help here? :)
  • To post as a guest, your comment is unpublished.
    GOE · 1 years ago
    Hi Sir,

    Would you please help me to add a table to "This is line 2" section in e-mail?
    For example; I have a table from A1 to J9. But the table is dynamic, not static. I mean it needs to select the table and then add to e-mail to "This is line 2" line as table.

    Thanks.
  • To post as a guest, your comment is unpublished.
    Ateek Shaha · 1 years ago
    How can i include range of cells for E.g.: C10:E40 of same sheet of button with same format in body of mail.
  • To post as a guest, your comment is unpublished.
    raguirre6776@gmail.com · 1 years ago
    How can I include a cell reference as a CC in the email using the above VBA code?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Hi Robert,
      Supposing you want to reference cell A1 in the CC field, please apply the below code.

      Private Sub CommandButton1_Click()
      'Updated by Extendoffice 2017/9/14
      Dim xOutApp As Object
      Dim xOutMail As Object
      Dim xMailBody As String
      On Error Resume Next
      Set xOutApp = CreateObject("Outlook.Application")
      Set xOutMail = xOutApp.CreateItem(0)
      xMailBody = "Body content" & vbNewLine & vbNewLine & _
      "This is line 1" & vbNewLine & _
      "This is line 2"
      On Error Resume Next
      With xOutMail
      .To = "Email Address"
      .CC = Range ("A1")
      .BCC = ""
      .Subject = "Test email send by button clicking"
      .Body = xMailBody
      .Display 'or use .Send
      End With
      On Error GoTo 0
      Set xOutMail = Nothing
      Set xOutApp = Nothing
      End Sub
  • To post as a guest, your comment is unpublished.
    Paul · 1 years ago
    How to I enter today's date in the 'Subject' line?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Hi Paul,
      Try the below code. Hope I can help. Thank you for your comment.

      Private Sub CommandButton1_Click()
      'Updated by Extendoffice 2019/12/13
      Dim xOutApp As Object
      Dim xOutMail As Object
      Dim xMailBody As String
      On Error Resume Next
      Set xOutApp = CreateObject("Outlook.Application")
      Set xOutMail = xOutApp.CreateItem(0)
      xMailBody = "Body content" & vbNewLine & vbNewLine & _
      "This is line 1" & vbNewLine & _
      "This is line 2"
      On Error Resume Next
      With xOutMail
      .To = "Email Address"
      .CC = ""
      .BCC = ""
      .Subject = "Your subject " & Date
      .Body = xMailBody
      .Display 'or use .Send
      End With
      On Error GoTo 0
      Set xOutMail = Nothing
      Set xOutApp = Nothing
      End Sub
  • To post as a guest, your comment is unpublished.
    tina.ellis@jpservices.com · 1 years ago
    I am running into a problem where the code works but will not pull the data from the cells I am telling it to. I know I am missing a command that tells it i want he wording in the cell to display instead of B8 to display in the email, can you help me?

    Private Sub CommandButton2_Click()
    'Updated by Extendoffice 2017/9/14
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    On Error Resume Next
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Payroll Information for [D4] is listed below" & vbNewLine & vbNewLine & _
    "[B8] [F8]" & vbNewLine & _
    "[B9] [F9]" & vbNewLine & _
    "[B10] [F10]" & vbNewLine & _
    "[B11] [F11]" & vbNewLine & _
    "[H13] [J13]" & vbNewLine & _
    "[H14] [J14]" & vbNewLine & _
    "[H15] [J15]" & vbNewLine & _
    "[H16] [J16]" & vbNewLine & _
    "[H17] [J17]" & vbNewLine & _
    "[H18] [J19]" & vbNewLine & _
    "[H19] [J19]"

    On Error Resume Next
    With xOutMail
    .To = "payroll@jpservices.com"
    .CC = ""
    .BCC = ""
    .Subject = "Offer Accepted by " & [D4]
    .Body = xMailBody
    .Display 'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
    End Sub
  • To post as a guest, your comment is unpublished.
    maxdown · 1 years ago
    Hi I used the code below and was wondering if I can send only the active sheet instead of the complete workbook I did try some code but with no luck

    I'm still to new to VBA coding

    Private Sub CommandButton1_Click()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim strbody As String
    Dim sAttach As String
    Dim sTo As String
    Dim sCC As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    'variable declarations for email body and attachment
    strbody = "Hi All;

    Display.
  • To post as a guest, your comment is unpublished.
    Courtney · 1 years ago
    Hi! Thank you so much for this. It's been fantastic help.

    Is it possible to send an active work sheet by pressing a button instead of the full workbook?

    Thanks!
  • To post as a guest, your comment is unpublished.
    Terence · 2 years ago
    Hi, I run a spreadsheet with 80 individual bar accounts and have used VBA code on this page with much success. However in the body of the email I would like to copy and paste the specific range of cells of an account when sending so the client can have a history. Can you help with the VBA code for this?
  • To post as a guest, your comment is unpublished.
    montuella@gmail.com · 2 years ago
    Hi,

    I have been working on a sheet, but i can't finish it. I hope u can help me :)

    The file its self must be a xltm (template) and it must attach the sheet it self in the mail.

    And a auto signature, then i would be very happy.

    Thanks in advance /Dr. Nang
  • To post as a guest, your comment is unpublished.
    Kris · 2 years ago
    Hi,

    Is there a way to change the file name to the current date when it attaches to the email?
  • To post as a guest, your comment is unpublished.
    Grant · 2 years ago
    How can I attach the Active Worksheet to the email when I press the button?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Grant,
      Please right click the button and select View Code, then copy below code between the Private Sub and the End Sub lines. Hope I can help. Thanks for your comment.

      Dim xFile As String
      Dim xFormat As Long
      Dim Wb As Workbook
      Dim Wb2 As Workbook
      Dim FilePath As String
      Dim FileName As String
      Dim OutlookApp As Object
      Dim OutlookMail As Object
      On Error Resume Next
      Application.ScreenUpdating = False
      Set Wb = Application.ActiveWorkbook
      ActiveSheet.Copy
      Set Wb2 = Application.ActiveWorkbook
      Select Case Wb.FileFormat
      Case xlOpenXMLWorkbook:
      xFile = ".xlsx"
      xFormat = xlOpenXMLWorkbook
      Case xlOpenXMLWorkbookMacroEnabled:
      If Wb2.HasVBProject Then
      xFile = ".xlsm"
      xFormat = xlOpenXMLWorkbookMacroEnabled
      Else
      xFile = ".xlsx"
      xFormat = xlOpenXMLWorkbook
      End If
      Case Excel8:
      xFile = ".xls"
      xFormat = Excel8
      Case xlExcel12:
      xFile = ".xlsb"
      xFormat = xlExcel12
      End Select
      FilePath = Environ$("temp") & "\"
      FileName = Wb.Name & Format(Now, "dd-mmm-yy h-mm-ss")
      Set OutlookApp = CreateObject("Outlook.Application")
      Set OutlookMail = OutlookApp.CreateItem(0)
      Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
      With OutlookMail
      .To = "skyyang@extendoffice.com"
      .CC = ""
      .BCC = ""
      .Subject = "kte features"
      .Body = "Please check and read this document."
      .Attachments.Add Wb2.FullName
      .Display
      '.Send
      End With
      Wb2.Close
      Kill FilePath & FileName & xFile
      Set OutlookMail = Nothing
      Set OutlookApp = Nothing
      Application.ScreenUpdating = True
  • To post as a guest, your comment is unpublished.
    marcus · 2 years ago
    I want to send the excel worksheet in the email but it doesnt send it. How do you write code to send document as email
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi marcus,
      The below VBA code can help you solving the problem.

      Sub SendWorkSheet()
      'Update 20190626
      Dim xFile As String
      Dim xFormat As Long
      Dim Wb As Workbook
      Dim Wb2 As Workbook
      Dim FilePath As String
      Dim FileName As String
      Dim OutlookApp As Object
      Dim OutlookMail As Object
      On Error Resume Next
      Application.ScreenUpdating = False
      Set Wb = Application.ActiveWorkbook
      ActiveSheet.Copy
      Set Wb2 = Application.ActiveWorkbook
      Select Case Wb.FileFormat
      Case xlOpenXMLWorkbook:
      xFile = ".xlsx"
      xFormat = xlOpenXMLWorkbook
      Case xlOpenXMLWorkbookMacroEnabled:
      If Wb2.HasVBProject Then
      xFile = ".xlsm"
      xFormat = xlOpenXMLWorkbookMacroEnabled
      Else
      xFile = ".xlsx"
      xFormat = xlOpenXMLWorkbook
      End If
      Case Excel8:
      xFile = ".xls"
      xFormat = Excel8
      Case xlExcel12:
      xFile = ".xlsb"
      xFormat = xlExcel12
      End Select
      FilePath = Environ$("temp") & "\"
      FileName = Wb.Name & Format(Now, "dd-mmm-yy h-mm-ss")
      Set OutlookApp = CreateObject("Outlook.Application")
      Set OutlookMail = OutlookApp.CreateItem(0)
      Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
      With OutlookMail
      .To = "skyyang@extendoffice.com"
      .CC = ""
      .BCC = ""
      .Subject = "kte features"
      .Body = "Please check and read this document."
      .Attachments.Add Wb2.FullName
      .Display
      '.Send
      End With
      Wb2.Close
      Kill FilePath & FileName & xFile
      Set OutlookMail = Nothing
      Set OutlookApp = Nothing
      Application.ScreenUpdating = True
      End Sub
  • To post as a guest, your comment is unpublished.
    kaitlyn k. · 2 years ago
    Do you have to be an excel user when pushing the button to send an email? or just the person receiving the email has to be an outlook user?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Good day,
      As the email need to be sent through Outlook after clicking the button in Excel, you must have Outlook installed in your computer to make it work.
  • To post as a guest, your comment is unpublished.
    John · 2 years ago
    Hi,

    How can I get the mail to automatically add my signature from outlook?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi John,
      The below VBA code can help you solve the problem. Thanks for your comment.

      Private Sub CommandButton1_Click()
      'Updated by Extendoffice 2019/6/26
      Dim xOutApp As Object
      Dim xOutMail As Object
      On Error Resume Next
      Set xOutApp = CreateObject("Outlook.Application")
      Set xOutMail = xOutApp.CreateItem(0)
      With xOutMail
      .Display 'or use .Send
      .To = "Email Address"
      .CC = ""
      .BCC = ""
      .Subject = "Test email send by button clicking"
      .HTMLBody = "This is a test email sending in Excel" & "
      " & .HTMLBody
      '.Send
      End With
      On Error GoTo 0
      Set xOutMail = Nothing
      Set xOutApp = Nothing
      End Sub
  • To post as a guest, your comment is unpublished.
    rasike001 · 2 years ago
    Hi There,
    Can anyone could help me on the following requirement?
    I have an excel sheet having two drop down lists.

    1 drop down list- list of departments

    2 drop down list- category

    What i want is when I select a department and category from the lists;(for example if I select "sales" in department and "monthly report" in category)

    I need to email the PDF version of that work sheet to the sales team with the email subject is monthly report.

    If i select "production" from the department list, the email should go to a group of people in the production.

    I appreciate if you can help me on this

    Rasike
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Rasike,
      Sorry can't help you with that. Welcome to post any question in our forum: https://www.extendoffice.com/forum.html to get more Excel support from out Excel professional or other Excel fans.
  • To post as a guest, your comment is unpublished.
    Abi · 2 years ago
    Can I reference the value in a cell in the subject with string? Some variation of the below?

    .Subject = "New Event:" & Target.Address = "$B$38"
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Abi,
      Please change the code to .Subject = "New Event:" & [B38].
      Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Laurie · 2 years ago
    Is it possible to, instead of sending the attachment in the email, to send a hyperlink to the file (located on SharePoint)?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Laurie,
      Can't help you with that. Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Glenn · 2 years ago
    using this VBA code, can I reference cell information within the body of the email? For instance, how would I reference cell values to the code below?

    xMailBody = "Body content" & vbNewLine & vbNewLine & _
    "This is line 1" & vbNewLine & _
    "This is line 2"

    Thanks,
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Glenn,
      Please apply the following code. Thank you for your comment.
      xMailBody = [B5]
  • To post as a guest, your comment is unpublished.
    Hannah · 2 years ago
    Is it possible to add a second email button within the same worksheet? When I try to do it, it is connecting to the code from the original email button. thanks.
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi,
      You need to assign different codes to each button.
  • To post as a guest, your comment is unpublished.
    erick · 2 years ago
    using this VBA code, can I reference cell information within the body of the email? For instance, how would I reference cell values to the code below?

    xMailBody = "Body content" & vbNewLine & vbNewLine & _
    "This is line 1" & vbNewLine & _
    "This is line 2"

    Also, using the (.TO = "email address") code. how can I have the "email address" pull in an email address from a cell in the column next to it.


    Thanks,
  • To post as a guest, your comment is unpublished.
    Reinaldo Batista · 2 years ago
    How can I attach the Active Workbook to the email when i press the button?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Good day,
      Just below ".Body = xMailBody" add the following
      .Attachments.Add ActiveWorkbook.FullName
  • To post as a guest, your comment is unpublished.
    Ravin Chatelall · 3 years ago
    Hi all first off a Big thank you, this post is very helpful and works for the attachment. This works for me but no updates are saved in the sheet you have to hit the save button. I would like the attachment to have whatever is currently in the excel sheet.

    I can accomplish this by using the excel built in E-mail feature but I wanted a button as I need to hardcode the specific email address.

    So in summary I would like to know:

    I would like to know if there is a way to: after a user open the excel workbook and made edits if the button will keep the attachment with the updates?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Good Day,
      The code has been optimized. Please have a try and thanks for your comment.

      Private Sub CommandButton1_Click()
      'Updated by Extendoffice 2017/9/14
      Dim xOutApp As Object
      Dim xOutMail As Object
      Dim xMailBody As String
      On Error Resume Next
      Set xOutApp = CreateObject("Outlook.Application")
      Set xOutMail = xOutApp.CreateItem(0)
      ActiveWorkbook.Save
      xMailBody = "Body content" & vbNewLine & vbNewLine & _
      "This is line 1" & vbNewLine & _
      "This is line 2"
      On Error Resume Next
      With xOutMail
      .To = "Email Address"
      .CC = ""
      .BCC = ""
      .Subject = "Test email send by button clicking"
      .Body = xMailBody
      .Attachments.Add ActiveWorkbook.FullName
      .Display 'or use .Send
      End With
      On Error GoTo 0
      Set xOutMail = Nothing
      Set xOutApp = Nothing
      End Sub
  • To post as a guest, your comment is unpublished.
    Tina · 3 years ago
    it only generates one email and will keep overwriting the contents instead of opening up multiply email drafts.
  • To post as a guest, your comment is unpublished.
    choppa · 3 years ago
    hi is it possible to set it up so that I dont have to press send - it automatically sends the email????
    • To post as a guest, your comment is unpublished.
      crystal · 3 years ago
      Hi,
      Please replace the line .Display with .Send in above VBA code.
  • To post as a guest, your comment is unpublished.
    Corey · 3 years ago
    Is it possbile to write the script so that when you click the button it will attach itself to the email as above but remove the button as well? so that the copy of the file being emailed no longer has the button on it?
    • To post as a guest, your comment is unpublished.
      Danie · 3 years ago
      Just below ".Body = xMailBody" add the following
      .Attachments.Add ActiveWorkbook.FullName
      • To post as a guest, your comment is unpublished.
        Ryno · 3 years ago
        Hi Danie.

        I added the portion as you said, but the email with the attached workbook still have the buttons on.
  • To post as a guest, your comment is unpublished.
    Alex · 3 years ago
    Hi, I am looking to send data from a pivot table data, can you please help