如何使用 VBA 在 MS Outlook 中获取规则的文本值?

How to get text values of rules in MS Outlook using VBA?

我正在尝试获取我在 MS Outlook 中设置的规则条件的文本值。

我创建了一个名为 "TestRule" 的规则,其条件基于消息 Body 中的文本(其中必须包含文本 "zzz")以及基于消息 Header 中的文本(其中必须包含文本 "aaa")。 (当然,这个规则可能永远不会运行,这里只是为了测试我是否能读懂规则中的条件。)规则和条件都启用了。

这是我正在使用的代码

Dim olRules As Outlook.Rules
Dim olRule As Outlook.Rule

Set olRules = Application.Session.DefaultStore.GetRules
Set olRule = olRules.Item("TestRule")

Debug.Print olRule.Conditions.Body.Text
Debug.Print olRule.Conditions.MessageHeader.Text

然而,debug.print 行都给出了 "Type mismatch" 的错误。

如何读取条件的当前值?

(我已经检查并且double-checked:那里一个名为"TestRule"的规则。)

GD刚果民主共和国,

您确定您的默认商店中存在名为 "TestRule" 的规则吗?

如果我执行你上面的代码,我会得到完美的结果(虽然没有打印任何东西,因为没有设置值。所以你上面代码中的语法是好的。

尝试添加:

Debug.Print TypeName(olRule)

如果您的 olRule 已实际设置,您的即时 Window 中的结果应该是 "Rule"。

所以整体代码应该是:

Dim olRules As Outlook.Rules
Dim olRule As Outlook.Rule

Set olRules = Application.Session.DefaultStore.GetRules
Set olRule = olRules.Item("TestRule")

Debug.Print TypeName(olRule)
Debug.Print olRule.Conditions.Body.Text
Debug.Print olRule.Conditions.MessageHeader.Text

希望这会引导您朝着正确的方向前进!

干杯!

GD刚果民主共和国,

我对你的问题付出了更多的努力,我想我已经弄清楚了你的类型不匹配的原因。

您可能向 "body" 条件和 "messageheader" 条件添加了一些关键字? 这些单独的条目被添加到一个数组中,即 "olRule.Conditions.Body.Text" 数组。

您的以下代码行;

olRule.Conditions.Body.Text
Debug.Print olRule.Conditions.MessageHeader.Text

本质上是在要求 'debug.print' 方法打印一个数组,但它不知道该怎么做。因为它不明白要打印数组的哪一部分。 根据您创建的条目数量,每个条目的标识符必然需要一个标识符来指向唯一的数组条目。

所以:

  • olRule.Conditions.Body.Text(0) 将指向 大批。
  • olRule.Conditions.Body.Text(1) 将指向第二个条目 在数组中。

有几种方法可以解决您的编码问题:

  1. 在行上设置断点:

    olRule.Conditions.Body.Text

这样执行就在执行代码行之前停止。 打开您的 'Locals Window'(通过 View|Locals Window)并打开 olRule.Text,您将看到与添加的数组条目一样多的条目。

  1. 将您的代码修改为如下所示

主子程序

Sub TestRule()
Dim olRules As Outlook.Rules
Dim olRule As Outlook.Rule

Set olRules = Application.Session.DefaultStore.GetRules
Set olRule = olRules.Item("TestRule")

Debug.Print TypeName(olRule)

printArray olRule.Conditions.Body.Text
printArray olRule.Conditions.MessageHeader.Text

End Sub

printArray 子程序

Private Sub printArray(ByRef pArr As Variant)
    Dim readString As Variant

    If (IsArray(pArr)) Then             'check if the passed variable is an array

        For Each readString In pArr

            If TypeName(readString) = "String" Then 'check if the readString is a String variable
                Debug.Print readString
            End If

        Next

    End If

End Sub

您也可以将第二个子例程集成到第一个子例程中,但更好的编码做法是在函数或单独的子例程中执行重复任务(然后您也可以将它用于同一模块中的其他方法:- ))

相信这将为您提供解决方案!

祝你好运!