对象变量或未设置块变量(错误91)请帮助

时间:2016-12-29 05:21:32

标签: vba outlook-vba

我正在尝试自动化我的团队使用的电子邮件功能,我也是这样做的新手所以请原谅这里的基本编码。我收到错误91消息对象变量或未设置块变量

以下是代码:

Sub Notification()  
  Dim outobj, mailobj
  Dim objUserPrmt1 As Object
  Dim strUserPrmt1
  Dim message, title, defaultValue As String

  message = "Enter your issue"
  title = "InputBox Demo"
  defaultValue = "No Issue"

  Set outobj = CreateObject("Outlook.Application")
  Set mailobj = outobj.CreateItem(0)
  Set strUserPrmt1 = objUserPrmt1.CreateItem(InputBox(message, title, defaultValue, 25, 45))

  With mailobj
    .To = "someone@somewhere.com"
    .Subject = "Notification:" strUserPrmt1
    .Body = "Test"
    '.Send
    .Display
  End With

  'Clear the memory
  Set outobj = Nothing
  Set mailobj = Nothing
  Set strUserPrmt1 = Nothing
  Set objUserPrmt1 = Nothing
End Sub

希望有人能告诉我失败的地方。

1 个答案:

答案 0 :(得分:1)

问题是你声明了一个对象变量objUserPrmt1,但你从未将它设置为等于任何东西,因此它的默认值为Nothing。然而,你试图在这一行中使用这一点:

Set strUserPrmt1 = objUserPrmt1.CreateItem(InputBox(message, title, defaultValue, 25, 45))

这无疑是引发错误的界限(你应该在问题中明确指出这一点)。

您似乎正在尝试使用Outlook对象模型的CreateItem方法。 Documentation表明这是Application对象的方法。由于已经拥有这样一个对象(outobj),因此根本不清楚objUserPrmt1的可能目的是什么。为什么不使用outobj

话虽如此,如果你用以下方法替换问题:

Set strUserPrmt1 = outobj.CreateItem(InputBox(message, title, defaultValue, 25, 45))

您可能仍会收到错误(尽管错误不一样)。这是因为我链接到的文档说CreateItem方法期望OlItemType constant但是你传给它一个字符串。

InputBox返回一个字符串,所以我认为@AlexP是正确的,你想要的可能只是:

strUserPrmt1 = InputBox(message, title, defaultValue, 25, 45)

由于字符串不是对象,因此不需要Set - 只是已分配。

我建议您只需从代码中删除objUserPrmt1即可。它没有任何理由存在,只是导致您的代码抛出错误。确保你也摆脱了这两行:

Set strUserPrmt1 = Nothing
Set objUserPrmt1 = Nothing

此外,将strUserPrmt1声明为字符串变量也没有什么坏处,尽管它当前的隐式声明是一个变量就足够了。