全部,我在visual studio中收到以下错误:"未声明选择。"
我正在尝试在vb中创建一个简单的单词应用程序,它允许我在文档中查找和替换多个值。我知道选择应该是文档的全部内容,我一直在研究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行。任何帮助将不胜感激。 谢谢:)
编辑:
为Word添加命名空间引用后,我现在在同一行上收到以下错误:
错误BC30469对非共享成员的引用需要对象引用。
答案 0 :(得分:1)
您可以使用(reference)
之类的内容进行选择Dim selection = Globals.ThisDocument.Application.Selection
但是使用选择很容易出现很多错误,并且始终不是Range
相反,您可以使用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