采用以下展望vba:
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时,我会遇到以下错误(即使参数类型返回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,因此请尝试设置mailItem=SelectedItem。