Note: The other languages of the website are Google-translated. Back to English
Log in  \/ 
x
or
x
Inscreva-se  \/ 
x

or

Como enviar email se uma determinada célula é modificada no Excel?

Este artigo fala sobre como enviar e-mail pelo Outlook se alguma célula em um determinado intervalo for modificada no Excel.

Enviar e-mail se a célula em um determinado intervalo for modificada com o código VBA


Enviar e-mail se a célula em um determinado intervalo for modificada com o código VBA


Se você precisar criar um novo e-mail automaticamente com a pasta de trabalho ativa anexada quando as células no intervalo A2: E11 forem modificadas em uma determinada planilha, o seguinte código VBA pode ajudá-lo.

1. Na planilha que você precisa enviar e-mail com base em sua célula modificada em um determinado intervalo, clique com o botão direito na guia da planilha e clique no botão Ver código no menu de contexto. Veja a imagem:

2. No popping up Microsoft Visual Basic para Aplicações janela, copie e cole o código VBA abaixo na janela Código.

Código VBA: enviar e-mail se a célula em um intervalo especificado for modificada no Excel

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 2017/9/12
    Dim xRgSel As Range
    Dim xOutApp As Object
    Dim xMailItem As Object
    Dim xMailBody As String
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Set xRg = Range("A2:E11")
    Set xRgSel = Intersect(Target, xRg)
    ActiveWorkbook.Save
    If Not xRgSel Is Nothing Then
        Set xOutApp = CreateObject("Outlook.Application")
        Set xMailItem = xOutApp.CreateItem(0)
        xMailBody = "Cell(s) " & xRgSel.Address(False, False) & _
            " in the worksheet '" & Me.Name & "' were modified on " & _
            Format$(Now, "mm/dd/yyyy") & " at " & Format$(Now, "hh:mm:ss") & _
            " by " & Environ$("username") & "."

        With xMailItem
            .To = "Email Address"
            .Subject = "Worksheet modified in " & ThisWorkbook.FullName
            .Body = xMailBody
            .Attachments.Add (ThisWorkbook.FullName)
            .Display
        End With
        Set xRgSel = Nothing
        Set xOutApp = Nothing
        Set xMailItem = Nothing
    End If
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

Notas:

1). No código, A2: E11 é o intervalo no qual você enviará e-mail.
2). Altere o corpo do e-mail conforme necessário em xMailBody linha no código.
3). Substitua o Email com o endereço de e-mail do destinatário alinhado .To = "Endereço de e-mail".
4). Altere o assunto do e-mail na linha .Subject = "Planilha modificada em" & ThisWorkbook.FullName.

3. aperte o outro + Q simultaneamente para fechar o Microsoft Visual Basic para Aplicações janela.

A partir de agora, qualquer célula no intervalo A2: E11 é modificada, um novo e-mail será criado com a pasta de trabalho atualizada anexada. E todos os campos especificados, como assunto, destinatário e corpo do email, serão listados no email. Por favor, envie o email.

Importante: O código VBA só funciona quando você usa o Outlook como seu programa de e-mail.


Artigos relacionados:


As melhores ferramentas de produtividade para escritório

O Kutools for Excel resolve a maioria dos seus problemas e aumenta sua produtividade em 80%

  • armadilha para peixes: Insira rapidamente fórmulas complexas, gráficos e qualquer coisa que você tenha usado antes; Criptografar células com senha; Criar lista de discussão e enviar emails ...
  • Super Formula Bar (edite facilmente várias linhas de texto e fórmula); Layout de leitura (ler e editar facilmente um grande número de células); Colar na faixa filtrada...
  • Mesclar células / linhas / colunas sem perder dados; Dividir o conteúdo das células; Combinar linhas / colunas duplicadas... Evite células duplicadas; Comparar intervalos...
  • Selecione Duplicado ou Único Linhas; Selecione linhas em branco (todas as células estão vazias); Super Find e Fuzzy Find em muitos livros; Seleção aleatória ...
  • Cópia exata Várias células sem alterar a referência da fórmula; Criação automática de referências para várias folhas; Inserir marcadores, Caixas de seleção e mais ...
  • Extrair Texto, Adicionar texto, remover por posição, Remover Espaço; Criar e imprimir subtotais de paginação; Converter entre conteúdo de células e comentários...
  • Super Filtro (salvar e aplicar esquemas de filtro a outras planilhas); Classificação Avançada por mês / semana / dia, frequência e mais; Filtro Especial por negrito, itálico ...
  • Combine pastas de trabalho e planilhas; Mesclar tabelas com base em colunas-chave; Divida os dados em várias folhas; Conversão em lote de xls, xlsx e PDF...
  • Mais de 300 recursos poderosos. Suporta Office / Excel 2007-2019 e 365. Suporta todos os idiomas. Fácil implantação em sua empresa ou organização. Teste gratuito de 30 dias com recursos completos. Garantia de devolução do dinheiro em 60 dias.
guia kte 201905

Guia do Office traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
officetab bottom
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.
    HumAnCK · 8 months ago
    Hello, i was trying to send emails on my sheet using one value changed on the sheet. If on column H the status will be changed to ="4" the Order ID in the left should be send to one user. The sheet works dynamicly so i have a Range from D9:D140 where order id's are stored and status changes are made in the same range on H9:H140. How can i reach the goal to do so and send the Order ID to my customer when status has been changed to ="4" ?
  • To post as a guest, your comment is unpublished.
    james2706 · 2 years ago
    Hello. How do I modify the code so that an e-mail is sent to another e-mail address if another range of cells is edited?
    • To post as a guest, your comment is unpublished.
      joseph · 2 years ago
      Any help on this request? I am having same issue. I want to add multiple email address per row, but when I change one row, the entire worksheet changes. How can I limit the changes only to one row?
      • To post as a guest, your comment is unpublished.
        Pawel · 1 years ago
        Edit linie:
        1). In the code, A2:E11 is the range you will send email based on.
        and
        3). Replace the Email Address with the recipient email address in line .To = "Email Address".

        Works fine.
        • To post as a guest, your comment is unpublished.
          Owen · 1 years ago
          Can you please explain this further. How do you repeat the code to send to a different email based on another range being modified. I have tried copy and pasting the code below and changing as per your comment, but still only the first range seems to execute the command and write the email.
  • To post as a guest, your comment is unpublished.
    Ioana · 2 years ago
    hi; is there a way to change text displayed using information from other cells (from first row and first column)? for example, if I change cell K15, I want to include in the message info on cells A15 and K1? what should I change in the code? thank you very much
    • To post as a guest, your comment is unpublished.
      laya · 7 months ago
      hi Laona. do u find out how can do this?

  • To post as a guest, your comment is unpublished.
    jimmy@globeways.com · 2 years ago
    I have tried above VBA code: Send email if cell in a specified range is modified in Excel. This VBA works for me except sending email. When the data is modified in the given range an email is automatically generated with modified cell details. However, the email is not automatically sending to the recipient and the user has to click send button in the email. What I am looking here is, the email has to send to the recipients automatically when it is generated. Please help me to provide a code for this. Many thanks
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Jimmy Joseph,
      Please replace the line ".Display" with ".Send". Hope I can help. Thanks for commenting.
  • To post as a guest, your comment is unpublished.
    sagar · 2 years ago
    if i have to send that entire row then?
  • To post as a guest, your comment is unpublished.
    Brad · 2 years ago
    Great information.
    Question regarding the information that can be added to the email.
    Using your example above....

    If you had a value in F4, how would you include the F4 Value in the email that was generated when D4 was modified??
  • To post as a guest, your comment is unpublished.
    Sonu · 2 years ago
    If i want to send the cell value instead of the address..then what shall I change in the code?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi,
      You can try the below VBA code.

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim xRgSel As Range
      Dim xOutApp As Object
      Dim xMailItem As Object
      Dim xMailBody As String
      On Error Resume Next
      Application.ScreenUpdating = False
      Application.DisplayAlerts = False
      Set xRg = Range("A2:E11")
      Set xRgSel = Intersect(Target, xRg)
      ActiveWorkbook.Save
      If Not xRgSel Is Nothing Then
      Set xOutApp = CreateObject("Outlook.Application")
      Set xMailItem = xOutApp.CreateItem(0)
      xMailBody = "Cell(s) " & xRgSel.Address(False, False) & _
      xRgSel.Value & _
      " in the worksheet '" & Me.Name & "' were modified on " & _
      Format$(Now, "mm/dd/yyyy") & " at " & Format$(Now, "hh:mm:ss") & _
      " by " & Environ$("username") & "."

      With xMailItem
      .To = "Email Address"
      .Subject = "Worksheet modified in " & ThisWorkbook.FullName
      .Body = xMailBody
      .Attachments.Add (ThisWorkbook.FullName)
      .Display
      End With
      Set xRgSel = Nothing
      Set xOutApp = Nothing
      Set xMailItem = Nothing
      End If
      Application.DisplayAlerts = True
      Application.ScreenUpdating = True
      End Sub
      • To post as a guest, your comment is unpublished.
        Gurpreet singh · 8 months ago
        What if we only want the updated comments in that cell an not the entire cell value
        It should show only the latest comments added in the cell

  • To post as a guest, your comment is unpublished.
    Mahadev · 3 years ago
    Dear Admin,


    I need your help,



    I have an excel to monitor daily work done details by our worker from the field, so is this possible to trigger a mail from excel sheet if that guy failed to update the data in that excel sheet on given time.
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi,
      Can't help with this.
  • To post as a guest, your comment is unpublished.
    sjones · 3 years ago
    I was able to create the macro, however I'm having a problem. I would like to automatically send an email when a cell reaches a certain threshold. The cell is a formula. When the calculation sum goes below the said threshold it doesn't do anything; however, if I type directly into the cell it will process the macro as planned. Does the formula mess up the macro?
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Sissy Jones,
      The method in this article: How to automatically send email based on cell value in Excel?
      https://www.extendoffice.com/documents/excel/4656-excel-send-email-based-on-cell-value.html may help you solve the problem.
  • To post as a guest, your comment is unpublished.
    pakxrohn@gmail.com · 3 years ago
    I am stuck in below VB code. I am trying to get email notification to the user where the data has been changed. Email is working but when I make any change email initiated at once but I want email when excel sheet is saved and closed after making all the changes to all users who impacted. Also this should be working for any of the sheets in entire excel workbook.

    Please help...

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    '****Declaration of objects and variables******

    Dim xRgSel As Range Dim xOutApp As Object Dim xMailItem As Object Dim xMailBody As String Dim mailTo As String

    On Error Resume Next

    Sheets("TargetSheet").Range("TargetRange").Select

    Application.ScreenUpdating = False Application.DisplayAlerts = False

    'Set xRg = Range("A" & Rows.Count).End(xlUp).Row

    Set xRg = Range("A2:DA1000")
    Set xRgSel = Intersect(Target, xRg)


    ActiveWorkbook.Save
    '**********Outlook Application Opening***********

    If Not xRgSel Is Nothing Then

    Set xOutApp = CreateObject("Outlook.Application")
    Set xMailItem = xOutApp.CreateItem(0)

    xMailBody = "Cell(s) " & xRgSel.Address(False, False) & _
    " in the worksheet '" & Me.Name & "' were modified on " & _
    Format$(Now, "mm/dd/yyyy") & " at " & Format$(Now, "hh:mm:ss") & _
    " by " & Environ$("username") & "."
    '***********Finding recipient List************

    If Cells(xRgSel.Row, "A").Value = "Pankaj" Then

    mailTo = "pank12***@gmail.com"

    End If

    If Cells(xRgSel.Row, "A").Value = "Nitin" Then

    mailTo = "pank****@gmail.com"

    End If

    If Cells(xRgSel.Row, "A").Value = "Chandan" Then

    mailTo = "pakxro**@gmail.com"

    End If
    '*************Email composing*************

    With xMailItem

    .To = mailTo
    .Subject = "Worksheet modified in " & ThisWorkbook.FullName
    .Body = xMailBody
    '.Attachments.Add (ThisWorkbook.FullName)
    .Display

    End With

    Set xRgSel = Nothing
    Set xOutApp = Nothing
    Set xMailItem = Nothing

    End If

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    End Sub
    • To post as a guest, your comment is unpublished.
      crystal · 3 years ago
      Dear Pankaj Shukla,
      Post your Excel question to our forum: https://www.extendoffice.com/forum.html to get more supports about Excel from our Excel professional.