Skip i'r prif gynnwys

Sut i anfon e-bost os yw'r botwm wedi'i glicio yn Excel?

Gan dybio bod angen i chi anfon e-bost trwy Outlook trwy glicio botwm yn nhaflen waith Excel, sut allwch chi wneud? Bydd yr erthygl hon yn cyflwyno dull VBA i'w gyflawni mewn manylion.

Anfon e-bost os yw'r botwm wedi'i glicio gyda chod VBA


Anfon e-bost os yw'r botwm wedi'i glicio gyda chod VBA

Gwnewch fel a ganlyn i anfon e-bost trwy Outlook os yw Botwm Gorchymyn yn cael ei glicio yn llyfr gwaith Excel.

1. Mewnosodwch Botwm Gorchymyn yn eich taflen waith trwy glicio Datblygwr > Mewnosod > Botwm Gorchymyn (Rheoli ActiveX). Gweler y screenshot:

2. De-gliciwch y Botwm Gorchymyn wedi'i fewnosod, yna cliciwch Gweld y Cod o'r ddewislen clicio ar y dde fel y dangosir isod.

3. Yn yr agoriad Microsoft Visual Basic ar gyfer Ceisiadau ffenestr, disodli'r cod gwreiddiol yn ffenestr y Cod gyda'r sgript VBA ganlynol.

Cod VBA: Anfon e-bost os yw'r botwm wedi'i glicio yn 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

Nodiadau:

1). Newidiwch y corff e-bost yn ôl yr angen yn y xMailCorff llinell yn y cod.

2). Amnewid y Cyfeiriad e-bost gyda'r cyfeiriad e-bost derbynnydd yn unol .To = "Cyfeiriad E-bost".

3). Nodwch y derbynwyr Cc a Bcc yn ôl yr angen .CC = “” ac .Bcc = “” adran.

4). Newid y pwnc e-bost yn unol .Subject = "Anfon e-bost prawf trwy glicio botwm".

4. Gwasgwch y Alt + Q allweddi ar yr un pryd i gau'r Microsoft Visual Basic ar gyfer Ceisiadau ffenestr.

5. Diffoddwch y Modd Dylunio trwy glicio Datblygwr > Modd Dylunio. Gweler y screenshot:

O hyn ymlaen, bob tro y byddwch chi'n clicio ar y Botwm Gorchymyn, bydd e-bost yn cael ei greu yn awtomatig gyda derbynwyr, pwnc a chorff penodol. Anfonwch yr e-bost trwy glicio ar y anfon botwm.

Nodyn: Dim ond pan fyddwch chi'n defnyddio Outlook fel eich rhaglen e-bost y mae'r cod VBA yn gweithio.

Yn hawdd anfon e-bost trwy Outlook yn seiliedig ar feysydd y rhestr bostio a grëwyd yn Excel:

Mae adroddiadau Anfon E-byst cyfleustodau Kutools ar gyfer Excel yn helpu i anfon e-bost trwy Outlook yn seiliedig ar feysydd rhestr bostio a grëwyd yn Excel.
Dadlwythwch a rhowch gynnig arni nawr! (llwybr am ddim 30 diwrnod)


Erthyglau cysylltiedig:

Offer Cynhyrchiant Swyddfa Gorau

🤖 Kutools AI Aide: Chwyldro dadansoddi data yn seiliedig ar: Cyflawniad Deallus   |  Cynhyrchu Cod  |  Creu Fformiwlâu Personol  |  Dadansoddi Data a Chynhyrchu Siartiau  |  Invoke Swyddogaethau Kutools...
Nodweddion Poblogaidd: Darganfod, Amlygu neu Adnabod Dyblygiadau   |  Dileu Rhesi Gwag   |  Cyfuno Colofnau neu Gelloedd heb Colli Data   |   Rownd heb Fformiwla ...
Super-edrych: VLookup Meini Prawf Lluosog    VLookup Gwerth Lluosog  |   VLookup Ar Draws Taflenni Lluosog   |   Edrych Niwlog ....
Rhestr gwympo Uwch: Creu Rhestr Gollwng yn Gyflym   |  Rhestr Gollwng Dibynnol   |  Rhestr Gollwng Aml-ddewis ....
Rheolwr Colofn: Ychwanegu Nifer Penodol o Golofnau  |  Symud Colofnau  |  Toglo Statws Gwelededd Colofnau Cudd  |  Cymharwch Ystodau a Cholofnau ...
Nodweddion dan Sylw: Ffocws ar y Grid   |  Golwg Dylunio   |   Bar Fformiwla Mawr    Rheolwr Llyfr Gwaith a Thaflen   |  Llyfrgell Adnoddau (Testun Auto)   |  Dewiswr Dyddiad   |  Cyfuno Taflenni Gwaith   |  Amgryptio/Dadgryptio Celloedd    Anfon E-byst trwy Restr   |  Hidlo Super   |   Hidlo Arbennig (hidlo mewn print trwm/italig/strikethrough...) ...
15 Set Offer Gorau12 Testun offer (Ychwanegu Testun, Dileu Cymeriadau,...)   |   50 + Siart Mathau (Siart Gantt,...)   |   40+ Ymarferol Fformiwlâu (Cyfrifwch oedran yn seiliedig ar ben-blwydd,...)   |   19 mewnosod offer (Mewnosod Cod QR, Mewnosod Llun o'r Llwybr,...)   |   12 Trosi offer (Rhifau i Eiriau, Trosi arian cyfred,...)   |   7 Uno a Hollti offer (Rhesi Cyfuno Uwch, Celloedd Hollt,...)   |   ... a mwy

Supercharge Eich Sgiliau Excel gyda Kutools ar gyfer Excel, a Phrofiad Effeithlonrwydd Fel Erioed Erioed. Kutools ar gyfer Excel Yn Cynnig Dros 300 o Nodweddion Uwch i Hybu Cynhyrchiant ac Arbed Amser.  Cliciwch Yma i Gael Y Nodwedd Sydd Ei Angen Y Mwyaf...

Disgrifiad


Mae Office Tab yn dod â rhyngwyneb Tabbed i Office, ac yn Gwneud Eich Gwaith yn Haws o lawer

  • Galluogi golygu a darllen tabbed yn Word, Excel, PowerPoint, Cyhoeddwr, Mynediad, Visio a Phrosiect.
  • Agor a chreu dogfennau lluosog mewn tabiau newydd o'r un ffenestr, yn hytrach nag mewn ffenestri newydd.
  • Yn cynyddu eich cynhyrchiant 50%, ac yn lleihau cannoedd o gliciau llygoden i chi bob dydd!
Comments (74)
Rated 3.5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Why is it that the filename of the attachment has the %20 filled in for the spaces? How to remove them and have the original file name, Price Discrepancy form.xlsm instead of Price%20Discrepancy%20form.xlsm?
Thank you.
This comment was minimized by the moderator on the site
Hi There,

I want to be able to attach a spreadsheet to an email and send it off, however, the difference is in the spreadsheet there is a date in cell A1 and description of works in cell A3, I want to be able to combine those and rename the spreadsheet to the attachments as per the date and description of works.

Thanks
This comment was minimized by the moderator on the site
Hi Fadi,
The following VBA code can do you a favor. Please give it a try. Thank you.
Private Sub CommandButton1_Click()

    'Update 20221123
    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
    Application.DisplayAlerts = True
    
    FileName = Format(ActiveSheet.Range("A1").Value, "dd-mmm-yy") & " " & ActiveSheet.Range("A3").Value
    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") & "\"

    Set OutlookApp = CreateObject("Outlook.Application")
    Set OutlookMail = OutlookApp.CreateItem(0)
    Debug.Print FilePath & FileName & xFile
    Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
    With OutlookMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Type your subject here"
        .Body = "Type your email body here."
        .Attachments.Add Wb2.FullName
        .Display
'        .Send
    End With
    Wb2.Close
    Kill FilePath & FileName & xFile
    Set OutlookMail = Nothing
    Set OutlookApp = Nothing
    Application.ScreenUpdating = True
    Application.DisplayAlerts = False

End Sub
This comment was minimized by the moderator on the site
Hello Guys,

Could you please help me with a VB code which should expand, Ungroup or Unhide base on if cell is selected with X and Y value
This comment was minimized by the moderator on the site
Hi Santosh,
I don't quite understand what you mean. You may need to attach a screenshot or a sample file to describe the problem you encountered more clearly.
This comment was minimized by the moderator on the site
Hi,
In my excel there is an chart, is there a way that when the button is pressed, the email is generated with the chart included into the body of the email?
Rated 3.5 out of 5
This comment was minimized by the moderator on the site
Hi Jack,
The following VBA code can do you a favor. After clicking the button, a dialog box will pop up, please enter the name of the chart you will include in your email body.
In the code, please change "Sheet1" to the name of the sheet that contains the chart you will send.
Private Sub CommandButton1_Click()
'Updated by Extendoffice 20220826
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xStartMsg As String
    Dim xEndMsg As String
    Dim xChartName As String
    Dim xChartPath As String
    Dim xPath As String
    Dim xChart As ChartObject
    On Error Resume Next
    xChartName = Application.InputBox("Please enter the chart name:", "KuTools for Excel", , , , , , 2)
    If xChartName = "" Then Exit Sub
    Set xChart = Sheets("Sheet1").ChartObjects(xChartName) 'Change "Sheet1" to your worksheet name
    If xChart Is Nothing Then Exit Sub
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xStartMsg = "<font size='5' color='black'> Good Day," & "<br> <br>" & "Please find the chart below: " & "<br> <br> </font>"
    xEndMsg = "<font size='4' color='black'> Many Thanks," & "<br> <br> </font>"
    xChartPath = Application.ActiveWorkbook.Path & "\" & Environ("USERNAME") & VBA.Format(VBA.Now(), "DD_MM_YY_HH_MM_SS") & ".bmp"
    xPath = "<p align='Left'><img src="/%20&%20"cid:" & Mid(xChartPath, InStrRev(xChartPath, "\") + 1) & """  width=700 height=500 > <br> <br>"
    xChart.Chart.Export xChartPath
    With xOutMail
        .To = ""
        .Subject = "Add Chart in outlook mail body"
        .Attachments.Add xChartPath
        .HTMLBody = xStartMsg & xPath & xEndMsg
        .Display
    End With
    Kill xChartPath
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub
This comment was minimized by the moderator on the site
Hi

I'm trying the initial request to simply have a button to open a new email but it doesn't seem to work.

Wondering if it has something to do with the " 'Updated by Extendoffice 2017/9/14" date.

Please let me know how to update this so I can get the button working :)
This comment was minimized by the moderator on the site
Hi Jonathan Matthias,
This line 'Updated by Extendoffice 2017/9/14" is a remark we give to the VBA code, which has nothing to do with the running of the VBA code.
Please make sure that CommandButton1 in the first line of the code is the same name as your button.
The name of the button will be displaysed in the Name Box after selecting it. See the screenshot below.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/email_button.png
This comment was minimized by the moderator on the site
Hi everyone,

On the lines of the email I'm trying right 4 lines of text and even adding "vbNewLine" is returning some errors. Also I'm trying to reference a column on the email subject and isn't showing anything. I really would appreciate any help.

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 = "Hi Kaitlyn," & vbNewLine & vbNewLine & _
"Please see the attached NPI form for for you review and approval." & vbNewLine & vbNewLine _
"Many thanks in advance, Liz"

On Error Resume Next
With xOutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = "Updated NPI Form" & (B5)
.Body = xMailBody
.Attachments.Add ActiveWorkbook.FullName
.Display 'or use .Send
End With
On Error GoTo 0
Set xOutMail = Nothing
Set xOutApp = Nothing
End Sub
Sub GroupBox542_Click()
End Sub
This comment was minimized by the moderator on the site
Hi Camila,
The following VBA code can do you a favor. Please give it a try. Thank you.
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 = "Hi Kaitlyn," & vbNewLine & _
               "The second line" & vbNewLine & _
              "Please see the attached NPI form for for you review and approval." & vbNewLine & _
              "Many thanks in advance, Liz"
                  On Error Resume Next
    With xOutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Updated NPI Form" & Range("B5")
        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub
This comment was minimized by the moderator on the site
How do I add code so that when the user submits the form via email to prompt them to include their name
This comment was minimized by the moderator on the site
Hi Susy Fong,
I don't quite understand what you mean. Can you explain it more specifically?
This comment was minimized by the moderator on the site
Hi, your tutorial has been very useful but if I wanted to include a range in the mail body instead of a string how would I go about that. Currently replacing the strings by referencing the cells is not working eg. xMailBody = ThisWorkbook.Activeworksheet("sheet1").Range("A2:F40") does not work
This comment was minimized by the moderator on the site
Activeworksheet("sheet1").Range("A2:F40").Value will work
This comment was minimized by the moderator on the site
Hi, perfect. Thank you. Is there any possibility to set also from which mail adress should be the mail sent? (in Outlook, I have two adresses, it automatically set one adress, but I need the second just for this makro) Thanks
This comment was minimized by the moderator on the site
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.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations