In trying to read the current word (where the cursor is) of a word document in a VSTO add-in with the following code :
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
It throws an excepetion Object reference not set to an instance of an object
at the sText = mobjApp.Selection.Text
line and I don't know what I am doing wrong. Haven't I already initialized mobjApp to a new instance ?