简体   繁体   中英

An Explicit conversion exists when working with word in C#

This code gets the active inspector window ie the compose mail window and performs the search and replace function for the body of the email.

But I am getting an error:

Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Word.Range'. An explicit conversion exists (are you missing a cast?)

Code here for your reference..

 private void button1_Click(object sender, RibbonControlEventArgs e)
    {
          Outlook.Inspector uiInspector = Globals.ThisAddIn.Application.ActiveInspector();
          object uiObject = uiInspector.CurrentItem;
          if (uiObject is Outlook.MailItem && uiInspector.IsWordMail())
          {
              Outlook.MailItem uiItem = (Outlook.MailItem)uiObject;
              Word.Document uiDoc = uiInspector.WordEditor as Word.Document;
              if (uiDoc != null)
              {
                  ***Word.Find uiFind = uiDoc.Range().Find;***
                  uiFind.Text = "ASA^$^$^#^#^#^#^#";
                  while (uiFind.Execute())
                  {
                      Microsoft.Office.Interop.Word.Range rng = uiFind.Parent;
                      rng.Hyperlinks.Add(rng, "http://stack.com=" + rng.Text + "outlook2007");
                      rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                  }
              }
          }
  }

How can I rectify this error?

You need to cast this line:

Microsoft.Office.Interop.Word.Range rng = uiFind.Parent;

to

var rng = uiFind.Parent as Microsoft.Office.Interop.Word.Range;

Try

Microsoft.Office.Interop.Word.Range rng = (Microsoft.Office.Interop.Word.Range)uiFind.Parent;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM