Outlook加载项错误

时间:2018-08-07 16:33:25

标签: vb.net outlook vsto

我正在创建一个插件,允许用户单击一个按钮,它会打开一个新电子邮件并自动填充字段,并让他们在发送电子邮件之前编辑正文。

我遇到了一个错误,该错误不允许我使用Outlook.Application

  

错误BC30111“应用程序”是接口类型,不能用作   表达式。

我在做什么错了?

我的代码:

Imports Microsoft.Office.Interop.Outlook
Imports Microsoft.Office.Tools.Ribbon

Public Class Ribbon1
    Private olMailItem As Object
    Private olImportanceHigh As OlImportance

    Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button1.Click

        Dim obApp As Object
        Dim NewMail As MailItem

        obApp = Outlook.Application
        NewMail = obApp.CreateItem(olMailItem)

        'You can change the concrete info as per your needs
        With NewMail
            .Subject = " Test Email"
            .To = "example@mail.com"
            .Body = "This is just a test email template with Outlook VBA" & vbCrLf & vbCrLf & vbCrLf & "Yours Truly," & vbCrLf & vbCrLf & "John Smith"
            .Importance = olImportanceHigh
            .Display
        End With

        obApp = Nothing
        NewMail = Nothing

    End Sub
End Class

2 个答案:

答案 0 :(得分:1)

您的VSTO加载项有一个入口点。这可能是一个Partial Class,可能称为ThisAddIn,使用ThisAddIn_StartupThisAddIn_Shutdown之类的方法(根据this article)。

该类继承了一个公开Application类型的Outlook.Application属性的类-这就是您要使用的对象。

因此,在启动时将其传递给Ribbon1实例:

Private Sub ThisAddIn_Startup(object sender, System.EventArgs e) Handles Something(?).Startup
    Dim ribbon As Ribbon1 = New Ribbon1(Me.Application)
    ' ...
End Sub

为您的Ribbon1类公开一个构造函数,以便您可以传递Application实例:

Private olApp As Outlook.Application

Public Sub New(ByVal app As Outlook.Application)
    olApp = app
End Sub

现在删除本地obApp As Outlook.Application声明,并改用从构造函数传递的实例。


编辑:从头开始。通读我链接的文章,有一个 全局实例Application随时可用-只需使用它即可:

obApp = Globals.ThisAddIn.Application

这样,您的Ribbon1类不需要通过其构造函数接收Application实例。虽然,使用全局变量是否是更好的设计还是有争议的。

答案 1 :(得分:0)

根据您的代码进行的更正-声明为obApp as Outlook.Application

在创建对象实例和处置对象时添加了Set

Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button1.Click

    Dim obApp As Outlook.Application
    Dim NewMail As MailItem

    Set obApp = New Outlook.Application
    Set NewMail = obApp.CreateItem(olMailItem)

    'You can change the concrete info as per your needs
    With NewMail
        .Subject = " Test Email"
        .To = "example@mail.com"
        .Body = "This is just a test email template with Outlook VBA" & vbCrLf & vbCrLf & vbCrLf & "Yours Truly," & vbCrLf & vbCrLf & "John Smith"
        .Importance = olImportanceHigh
        .Display
    End With

    Set obApp = Nothing
    Set NewMail = Nothing

End Sub