VSTO for Word:对象引用未设置为对象的实例

时间:2018-03-12 14:26:38

标签: vb.net vsto

尝试使用以下代码读取VSTO加载项中word文档的当前单词(光标所在的位置):

Public Class MyRibbon
    Private Sub MyRibbon_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 mobjApp As Word.Application = New Word.Application
        Dim mobjRange As Word.Range

        Dim intCounter As Integer
        'mobjApp = CreateObject("Word.Application")
        'mobjRange = Nothing
        If mobjApp.Documents.Count = 0 Then
            'Exit Sub
        End If
        MsgBox("hehe" & mobjApp.Documents.Count)
        'With mobjApp.Selection
        Dim sText As String
        sText = mobjApp.Selection.Text
        If Trim(sText) = "" Or Len(Trim(sText)) = 1 Then
            mobjApp.Selection.Words.First.Select()
        End If
        sText = mobjApp.Selection.Text
        If Not Len(Trim(sText)) > 0 Then
            MsgBox("set your cursor on a word", vbInformation)
            Exit Sub
        End If
        'End With
        MsgBox(2)
        If mobjApp.Selection.Paragraphs.Count > 1 Then
            mobjRange = mobjApp.Selection.Paragraphs(1).Range
            mobjRange.Select()
        Else
            mobjRange = mobjApp.Selection.Range
        End If
        Dim a As String
        a = mobjRange.Text
        mobjRange.Copy()
        MsgBox(a)
        Clipboard.SetText(a)
    End Sub
End Class

它在Object reference not set to an instance of an object行引发了sText = mobjApp.Selection.Text,并且我不知道我做错了什么。我还没有将mobjApp初始化为新实例吗?

0 个答案:

没有答案