I am trying to do a search operation in active word document on a button click. And getting a error in my code is
The button is on a custom task pane
Error CS1061 'UserControl1' does not contain a definition for 'Application' and no accessible extension method 'Application' accepting a first argument of type 'UserControl1' could be found (are you missing a using directive or an assembly reference?) WordAddIn1 c:\users\veroot\source\repos\WordAddIn1\WordAddIn1\UserControl1.cs 29 Active
And the code is
private void button1_Click(object sender, EventArgs e)
{
object findText = textBox1.Text;
object missing = System.Type.Missing;
Word.Document document = this.Application.ActiveDocument;
Word.Range rng = document.Range(0, Type.Missing);
rng.Find.Highlight = 0;
rng.Find.Forward = true;
do
{
if (rng.HighlightColorIndex == WdColorIndex.wdYellow)
{
rng.HighlightColorIndex = WdColorIndex.wdRed;
rng.Font.ColorIndex = WdColorIndex.wdBlue;
}
int intPosition = rng.End;
rng.Start = intPosition;
} while (rng.Find.Execute("", missing, missing, missing, missing, missing, true,
missing, missing, missing, missing, missing, missing, missing, missing));
}
In a VSTO solution it's only possible to use the keyword this
to refer to the host Office application inside the ThisAddin
class. In all other classes, including the one for a UserControl, this
will refer to that class (the UserControl) and have no relation or connection to the host Office application. So in the case of the code shown in the question, this
refers to the UserControl class.
In order to refer to the Office application in which the VSTO add-in is running it's best to use the Globals
keyword. For example
Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
or
Word.Document doc = Globals.ThisAddIn.app.ActiveDocument;
where app
is a class-level field in the ThisAddin
class - example declaration:
public partial class ThisAddIn
{
public Word.Application app;
which is assigned in ThisAddin_Startup
- for example:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
app = this.Application;