採取以下前景VBA:展望2007+鑄造Application.ActiveExplorer.Selection.Item到Outlook.mailItem時TypeOf運算項目= Outlook.mailItem
Sub FileEmails()
Dim myOlExp As Outlook.Explorer
Dim myOlSel As Outlook.Selection
Set myOlExp = Application.ActiveExplorer
Set myOlSel = myOlExp.Selection
If myOlSel.Count = 0 Then
MsgBox "No objects selected."
Else
For Each SelectedItem In myOlSel
If (TypeOf SelectedItem Is Outlook.mailItem) Then
Dim mailItem As Outlook.mailItem
Set mailItem = SelectedItem
itemMessage = "The item is an e-mail message. The subject is " & mailItem.Subject & "."
mailItem.Display (False)
ElseIf (TypeOf SelectedItem Is Outlook.contactItem) Then
Dim contactItem As Outlook.contactItem
Set contactItem = SelectedItem
itemMessage = "The item is a contact. The full name is " & contactItem.Subject & "."
contactItem.Display (False)
ElseIf (TypeOf SelectedItem Is Outlook.AppointmentItem) Then
Dim apptItem As Outlook.AppointmentItem
Set apptItem = SelectedItem
itemMessage = "The item is an appointment." & apptItem.Subject & "."
ElseIf (TypeOf SelectedItem Is Outlook.taskItem) Then
Dim taskItem As Outlook.taskItem
Set taskItem = SelectedItem
itemMessage = "The item is a task. The body is " & taskItem.Body & "."
ElseIf (TypeOf SelectedItem Is Outlook.meetingItem) Then
Dim meetingItem As Outlook.meetingItem
Set meetingItem = SelectedItem
itemMessage = "The item is a meeting item. The subject is " & meetingItem.Subject & "."
End If
Next SelectedItem
expMessage = expMessage & itemMessage
MsgBox (expMessage)
End If
End Sub
如果我選擇在我的收件箱幾個項目並運行此代碼,它成功地識別出的SelectedItem是Outlook.mailItem,但我得到試圖投的SelectedItem到Outlook.MailItem(即使將typeof參數返回TRUE)時,出現以下錯誤:
Object variable or with block variable not set
我怎麼能執行此投?我基於以下.NET示例代碼(這使得使用TryCast的):
http://msdn.microsoft.com/en-us/library/ms268994.aspx
我還沒有測試過你的代碼,但這裏有幾點可能有幫助。 Outlook VBA與VB.NET不一樣。 VB.NET是後代,有很多改進。其中一項改進是您可以在塊級別聲明變量。對於VBA,變量只能在模塊或例程級別聲明。我不知道如果在循環中重新聲明變量會發生什麼情況,所以將所有'Dim'語句移到頂部。 VB.NET不使用'SET'。 VBA需要'SET'作爲對象,所以試試'Set mailItem = SelectedItem'。 – 2012-03-22 16:49:52
嗨託尼,內聯Dims罰款(雖然我會將他們移動到頂端無論如何),這是缺乏'SET'造成的問題(Doh!) - 我不介意,但我一直在寫.net和經典的asp應用程序多年 - AMAZED我沒有注意到我自己(有點尷尬!) - 無論如何 - 發佈作爲一個答案,我將它標記爲解決方案。乾杯。 – HeavenCore 2012-03-23 09:44:21