2011-07-01 75 views
1

我試着找出如何使用以下代碼段以編程方式處理多個消息對象,但遇到問題。最終,我想發送郵件到電子表格文件中的收件人列表。哪個對象和方法能以最簡單的方式完成這項工作?VBA:處理多個消息項目

Dim w As Outlook.Application 
    Dim wInbox As Outlook.MAPIFolder 
    Dim objOutlookMsg As Outlook.MailItem 
    Dim objOutlookRecip As Outlook.Recipient 

    Dim count, x, msgnum As Integer 
' Handle Microsoft outlook 
    Set w = GetObject(, "Outlook.Application") 
    If Err = ERR_APP_NOTRUNNING Then     ' Open new instance if none is running 
     Set w = New Outlook.Application 
     wInbox = w.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) 
    End If 

    'Count number of emails required 
    count = Cells(1, 2).End(xlDown).Row 
    msgnum = wInbox.Items.count 
    For x = 1 To count 
     Set objOutlookMsg = w.CreateItem(olMailItem) 
     msgnum = wInbox.Items.count 
    Next x 

-------編輯--------- 如果我像這樣處理代碼會怎麼樣?

Dim w As Outlook.Application 
    Dim wInbox As Outlook.MAPIFolder 
    Dim objOutlookMsg As Outlook.MailItem 
    Dim objOutlookRecip As Outlook.Recipient 

    Dim count, x, msgnum As Integer 
' Handle Microsoft outlook 
    Set w = GetObject(, "Outlook.Application") 
    If Err = ERR_APP_NOTRUNNING Then     ' Open new instance if none is running 
     Set w = New Outlook.Application 
    End If 
    wInbox = w.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) 

    'Count number of emails required 
    count = Cells(1, 2).End(xlDown).Row 
    msgnum = wInbox.Items.count 
    For x = 1 To count 
     Set objOutlookMsg = w.CreateItem(olMailItem) 
     msgnum = wInbox.Items.count 
    Next x 
+0

我看不到任何真正不尋常的在你的代碼。代碼停止在哪裏?或者它不工作的地方? – JMax

+0

如果Outlook已在運行,則您的代碼將失敗,因爲您只是在啓動新實例時才設置wInbox。你能提供更多細節嗎?你想發送相同的消息給多個收件人?您可以只發送一封郵件給收件人(或密件抄送)字段中的所有收件人嗎? –

+0

更具體地說,我在處理objOutlookMsg對象以處理多條消息時遇到問題。 – stanigator

回答

2

這個工作對我來說...

Sub TestOutlookSend() 

    Dim w As Outlook.Application 
    Dim wInbox As Outlook.MAPIFolder 
    Dim objOutlookMsg As Outlook.MailItem 
    Dim rngAddr As Range, recip As String 

     Set rngAddr = ThisWorkbook.Sheets("Sheet1").Range("A2") 

     Set w = GetObject(, "Outlook.Application") 
     Set wInbox = w.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) 

     Do While rngAddr.Value <> "" 
      recip = rngAddr.Value 

      Set objOutlookMsg = w.CreateItem(olMailItem) 
      With objOutlookMsg 
       .To = recip 
       .Subject = "Hello " & recip 
       .Body = "A message for" & recip 
       .Send 
      End With 

      Set rngAddr = rngAddr.Offset(1, 0) 
     Loop 

End Sub 
+0

如果我不想立即發送它們,但將它們保持非活動狀態,該怎麼辦? – stanigator

+0

那麼不要發送它們?只需發表*。發送*行... –

+0

我想我對代碼正在尋找obOutlookMsg的消息感到困惑,就這些。 – stanigator