我仍在處理我在本主題的1st question中描述的問題。爲了簡短刷新,它是一個excel文件,其中包含電子郵件模板和附件列表,對於每個列表單元,我添加了打開給定單元模板的按鈕,使其發生一些更改,然後附加文件並將郵件顯示到用戶。用戶可以根據需要修改郵件,然後發送或不發送郵件。我已經嘗試了幾種下面描述的方法。 不幸的是,我現在在類模塊的問題上停滯不前,那簡短地描述了here。我已經創建了一個類模塊,如「EmailWatcher」,甚至使用方法的小組合描述here:EXCEL VBA,手動Outlook電子郵件發件人,類模塊問題
Option Explicit
Public WithEvents TheMail As Outlook.MailItem
Private Sub Class_Terminate()
Debug.Print "Terminate " & Now()
End Sub
Public Sub INIT(x As Outlook.MailItem)
Set TheMail = x
End Sub
Private Sub x_Send(Cancel As Boolean)
Debug.Print "Send " & Now()
ThisWorkbook.Worksheets(1).Range("J5") = Now()
'enter code here
End Sub
Private Sub Class_Initialize()
Debug.Print "Initialize " & Now()
End Sub
變化到以下形式不作任何改變:
Option Explicit
Public WithEvents TheMail As Outlook.MailItem
Private Sub Class_Terminate()
Debug.Print "Terminate " & Now()
End Sub
Public Sub INIT(x As Outlook.MailItem)
Set TheMail = x
End Sub
Private Sub TheMail_Send(Cancel As Boolean)
Debug.Print "Send " & Now()
ThisWorkbook.Worksheets(1).Range("J5") = Now()
'enter code here
End Sub
Private Sub Class_Initialize()
Debug.Print "Initialize " & Now()
End Sub
的模塊代碼如下:
Public Sub SendTo()
Dim r, c As Integer
Dim b As Object
Set b = ActiveSheet.Buttons(Application.Caller)
With b.TopLeftCell
r = .Row
c = .Column
End With
Dim filename As String, subject1 As String, path1, path2, wb As String
Dim wbk As Workbook
filename = ThisWorkbook.Worksheets(1).Cells(r, c + 5)
path1 = Application.ThisWorkbook.Path &
ThisWorkbook.Worksheets(1).Range("F4")
path2 = Application.ThisWorkbook.Path &
ThisWorkbook.Worksheets(1).Range("F6")
wb = ThisWorkbook.Worksheets(1).Cells(r, c + 8)
Dim outapp As Outlook.Application
Dim oMail As Outlook.MailItem
Set outapp = New Outlook.Application
Set oMail = outapp.CreateItemFromTemplate(path1 & filename)
subject1 = oMail.subject
subject1 = Left(subject1, Len(subject1) - 10) &
Format(ThisWorkbook.Worksheets(1).Range("D7"), "DD/MM/YYYY")
oMail.Display
Dim CurrWatcher As EmailWatcher
Set CurrWatcher = New EmailWatcher
CurrWatcher.INIT oMail
Set CurrWatcher.TheMail = oMail
Set wbk = Workbooks.Open(filename:=path2 & wb)
wbk.Worksheets(1).Range("I4") =
ThisWorkbook.Worksheets(1).Range("D7").Value
wbk.Close True
ThisWorkbook.Worksheets(1).Cells(r, c + 4) = subject1
With oMail
.subject = subject1
.Attachments.Add (path2 & wb)
End With
With ThisWorkbook.Worksheets(1).Cells(r, c - 2)
.Value = Now
.Font.Color = vbWhite
End With
With ThisWorkbook.Worksheets(1).Cells(r, c - 1)
.Value = "Was opened"
.Select
End With
End Sub
最後我做了這是工作的一類,我已經把一些控件,以檢查它,你可以從類看冒頓le代碼。但問題是,它沒有捕獲發送事件。這個類在sub的結尾處終止。將電子郵件完全留給用戶。問題是:哪裏出錯?或者如何在所謂的「等待模式」下離開課程模塊,或者其他建議? 我也考慮在'發件箱'中搜索郵件的方式,但發送事件的方式更受青睞。
謝謝大衛。我的宏觀確實取得了進展。但是我仍然有一個問題,那就是類在宏的末尾終止。將閱讀你的回覆關於郵件陷阱,希望它會有所幫助。 – Lincoln
非常感謝大衛。 – Lincoln