2013-01-09 32 views
1

我有以下幾行代碼。它在Outlook打開時工作正常,但即使Outlook關閉,我也希望它能夠正常工作。我將代碼保留在命令按鈕單擊事件中。如何在outlook關閉時發送郵件

Private Sub btnSend_Click() 
Dim OutApp As Object 
Dim OutMail As Object 
Set OutApp = GetObject("", Outlook.Application) 
OutApp.Session.Logon 
Set OutMail = OutApp.CreateItem(0) 
On Error Resume Next 
With OutMail 
    .To = "[email protected]" 
    .CC = "" 
    .BCC = "" 
    .Subject = "Test mail from Excel Sheet-OutLook Closed" 
    .Body = "This is body of the mail" 
    .Display 
    .Send 
    .ReadReceiptRequested = True 
End With 
On Error GoTo 0 
Set OutMail = Nothing 
Set OutApp = Nothing 
End Sub 

我試過它與GetObject和CreateObject方法。如果我在關閉Outlook後執行此代碼,它不會顯示任何錯誤,但它不會發送任何郵件。

以下幾行代碼發送郵件,但它們在Outlook的發件箱中排隊。當用戶打開Outlook時,只有他們從發件箱中移出。

Private Sub btnSend_Click() 
Dim OutApp As Object 
Dim OutMail As Object 
Set OutApp = CreateObject("Outlook.Application") 
Set OutMail = OutApp.CreateItem(0) 
On Error Resume Next 
With OutMail 
    .To = "[email protected]" 
    .CC = "" 
    .BCC = "" 
    .Subject = "Test mail from Excel Sheet-OutLook Closed" 
    .Body = "This is body of the mail" 
    .Display 
    .Send 
    .ReadReceiptRequested = True 
End With 
On Error GoTo 0 
Set OutMail = Nothing 
Set OutApp = Nothing 
End Sub 
+0

我沒有看到CreateObject代碼?這應該工作... –

+0

而不是GetObject(「」,Outlook.Application)我已經使用了CreateObject(Outlook.Application)和保持同行。 –

+0

如果我這樣寫,那麼郵件在發件箱中排隊。每當用戶打開前景那麼只有電子郵件被going.'' –

回答

1

您可以使用shell命令實際上打開Outlook發送mail.Precisely是

Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long 
Public Sub OpenOutlook() 
Dim ret As Long 
On Error GoTo aa 
ret = ShellExecute(Application.hwnd, vbNullString, "Outlook", vbNullString, "C:\", SW_SHOWNORMAL) 
If ret < 3 Then 

MsgBox "Outlook is not found.", vbCritical, "SN's Customised Solutions" 
End If 
aa: 
End Sub 

保持這種在一個單獨的模塊,並在您發送郵件從代碼中調用模塊之前。我正在努力的部分是如何隱藏這一點,使激活仍然與Excel

0

對於Outlook 2013,這是Outlook設置,而不是VBA代碼的問題。

  • 打開Outlook

  • 進入文件 - >選項 - >高級

  • 滾動到 '發送和接收' 標題,然後單擊 '發送/接收...' 按鈕

  • 在'設置組'所有帳戶''下,確保'執行 自動發送/接收退出'時檢查

這可確保Outlook關閉時發送OUTLOOK「發件箱」中的所有項目。這解決了我的問題。可能與其他版本的Outlook類似。

相關問題