首页 文章

当 TypeOf Item = Outlook.mailItem 时,Outlook 2007 将 Application.ActiveExplorer.Selection.Item 转换为 Outlook.mailItem

提问于
浏览
1

采取以下 Outlook 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 参数返回 true):

Object variable or with block variable not set

我该如何执行此投射?我基于以下.net 示例(使用 TryCast)创建此代码:

http://msdn.microsoft.com/en-us/library/ms268994.aspx

1 回答

  • 1

    我尚未测试您的代码,但以下几点可能会有所帮助。

    Outlook VBA 与 VB.NET 不同。 VB.NET 是后代,并且有很多改进。

    这些改进之一是可以在块级别声明变量。对于 VBA,只能在模块或例程级别声明变量。我不知道如果在循环中 re-declare 变量会发生什么,因此将所有 Dim 语句移到顶部。

    VB.NET 不使用 SET。 VBA 需要对对象进行设置,因此请尝试设置 mailItem = SelectedItem。

相关问题