2017-02-09 109 views
0

所有,我在Visual Studio中收到以下錯誤:「選擇沒有聲明。」選擇沒有聲明,但不知道如何聲明它

我想在vb中製作一個簡單的word應用程序,它允許我在文檔中查找和替換多個值。我知道選擇應該是文檔的全部內容,並且我一直在研究MSDN,但是我一定錯過了一些東西,因爲我一直無法知道我應該怎麼做來聲明要搜索哪個選擇。

我在我的項目中的兩個項目:

ThisDocument.vb:

Imports Microsoft.Office.Interop.Word.Range.Select 
Public Class ThisDocument 
    Private Sub ThisDocument_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup 
     Me.Paragraphs(1).Range.InsertParagraphAfter() 
     Me.Paragraphs(2).Range.Text = "This text was added programmatically." 
    End Sub 
    Private Sub ThisDocument_Shutdown() Handles Me.Shutdown 
    End Sub 
End Class 

和Charm.vb(這是一個帶狀項):

Option Explicit On 
Imports Microsoft.Office.Tools.Ribbon 
Imports Microsoft.Office.Interop.Word.WdFindWrap 
Imports Microsoft.Office.Interop.Word.WdReplace 
Imports Microsoft.Office.Interop.Word.WdFindMatch 
Public Class Charm 

    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 custNum As String = TB_CustNum.Text 
     With Selection.Find 
      .ClearFormatting() 
      .Text = "care" 
      .Replacement.ClearFormatting() 
      .Replacement.Text = custNum 
      .Execute(Replace:=wdReplaceAll, Forward:=True, 
       Wrap:=wdFindContinue) 
     End With 
    End Sub 
End Class 

錯誤發生在Charm.vb的第14行。任何幫助,將不勝感激。 謝謝:)

編輯:

添加一個字一個命名空間引用之後,我現在得到在同一行上出現以下錯誤:

錯誤BC30469參考非共享成員需要一個對象引用。

+1

'Selection'是Word.Application'的'成員 - 你不能沒有通過互操作限定它使用它,因爲全球的對象不能像他們在Word VBA。 – Comintern

+0

您可能需要爲Word.Application添加引用 – Deepesh

+0

我現在正在收到以下錯誤:錯誤BC30469對非共享成員的引用需要對象引用。 – Change

回答

1

你可以選擇喜歡的東西(reference

Dim selection = Globals.ThisDocument.Application.Selection 

但與選擇的工作很容易出現許多錯誤,而不是總是Range
相反,你可以使用範圍變量:

Dim doc as Document = Globals.ThisDocument 

Dim range As Range = doc.Range ' this is the main story Range without Headers and Footers 

With range.Find 
    .Execute(FindText:="care", ReplaceWith:=custNum, Replace:=wdReplaceAll, 
      Forward:=True, Format:=False, Wrap:=wdFindContinue) 
End With