Outlook VBA 如何在自定义对象中保存 MailItem 属性

Outlook VBA how to save MailItem in custom object property

我试图将 MailItem 对象存储在我的自定义对象的 属性 中以便稍后调用,但我收到以下错误:

Run-time error '91': Object variable or With block variable not set

这是我的 Class1:

Private vprop1 As String
Private vprop2 As String
Private vprop3 As MailItem

Property Get prop1() As String
    prop1 = vprop1
End Property

Property Let prop1(aValue As String)
    vprop1 = aValue
End Property

Property Get prop2() As String
    prop2 = vprop2
End Property

Property Let prop2(aValue As String)
    vprop2 = aValue
End Property

Property Get prop3() As MailItem
    prop3 = vprop3
End Property

Property Let prop3(aValue As MailItem)
    vprop3 = aValue
End Property

这是我的测试。错误引用了第三个 属性 赋值:var.prop3 = ...

Public Sub test()
    Set objsourcefolder = Application.Session.GetDefaultFolder(olFolderInbox)

    Dim var As Class1
    Set var = New Class1

    var.prop1 = "\folder\sub345"
    var.prop2 = "Email subject regarding 12345"
    var.prop3 = objsourcefolder.Items.Item(objsourcefolder.Items.count)

    Debug.Print var.prop1
    Debug.Print var.prop2
    Debug.Print var.prop3
    Debug.Print var.prop3.Subject
End Sub

非常感谢任何帮助!

因为 MailItem 是一个 object,您必须通过 Set 关键字设置引用它的任何变量并更改 Property Let(关联到 not- object 类型属性)到 Property Set(关联到 object 类型属性)

最后你不能使用 Debug.Print var.prop3 因为你的 Class1 类型没有任何 default 属性 它的 prop3 object 会员

以上所有结果:


class代码

Private vprop1 As String '<--| vprop1 is declared as of 'String' type, i.e. NOT as an 'object'
Private vprop2 As String '<--| vprop2 is declared as of 'String' type, i.e. NOT as an 'object'
Private vprop3 As MailItem '<--| vprop3 is declared as of 'MailItem' type, i.e. as an 'object'

Property Get prop1() As String
    prop1 = vprop1
End Property

Property Let prop1(aValue As String)
    vprop1 = aValue
End Property

Property Get prop2() As String
    prop2 = vprop2
End Property

Property Let prop2(aValue As String)
    vprop2 = aValue
End Property

Property Get prop3() As MailItem
    Set prop3 = vprop3 '<--| use 'Se't keyword
End Property

Property Set prop3(aValue As MailItem) '<--| use 'Property Set' instead of 'Property Let'
    Set vprop3 = aValue '<--| use 'Set' keyword
End Property

测试子代码

Public Sub test()
    Dim objsourcefolder As Folder
    Set objsourcefolder = Application.Session.GetDefaultFolder(olFolderInbox)

    Dim var As Class1
    Set var = New Class1

    var.prop1 = "\folder\sub345"
    var.prop2 = "Email subject regarding 12345"
    Set var.prop3 = objsourcefolder.Items.Item(objsourcefolder.Items.Count)

    Debug.Print var.prop1
    Debug.Print var.prop2
'    Debug.Print var.prop3 '<--| this would result in an 438 error
    Debug.Print var.prop3.Subject
End Sub