采取以下展望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时会出现以下错误(即使返回了typeof参数)真):
Object variable or with block variable not set
我如何执行此演员表?我将此代码基于以下.net示例(使用TryCast):
答案 0 :(得分:1)
我还没有测试过您的代码,但这里有几点可能有所帮助。
Outlook VBA与VB.NET不同。 VB.NET是后代,有很多改进。
其中一项改进是您可以在块级别声明变量。对于VBA,变量只能在模块或例程级别声明。我不知道如果你在循环中重新声明变量会发生什么,所以将所有Dim语句移到顶部。
VB.NET不使用SET。 VBA需要SET对象,因此请尝试设置mailItem = SelectedItem。