【发布时间】:2019-11-20 16:30:42
【问题描述】:
我知道如何搜索整个文档。我正在使用 foreach(doc.Sections 中的 Word.Section 段落)。但是如果我只想在选择中搜索呢?假设用户将选择文本然后进行搜索。然后我们只想在选择中搜索。我怎么能用 Foreach sicle 做到这一点? 现在我有这个代码:
app.Selection.HomeKey(Unit: WdUnits.wdStory);
while (WordsCount >= 1)
foreach (Word.Section paragraph in doc.Sections)
{
Word.Selection rngFound = FindAndReplace(app.Selection, searchTerm, ""); //searching and wrapping.
if (rngFound != null)
{
string foundNr = rngFound.Text;
string hyperlinkNr = foundNr.Replace((char)30, (char)45);
rngFound.Range.Hyperlinks.Add(rngFound.Range, hyperlink + hyperlinkNr);
}
WordsCount--;
我知道有多少字(我在找什么)。但是我怎么能说搜索功能我们只需要在选择中搜索。或该选择的范围。
这是我的搜索功能:
Word.Selection FindAndReplace(Word.Selection rngToSearch, object findText, object replaceWithText) //Find function
{
bool found = false;
//options
object matchCase = false;
object matchWholeWord = true;
object matchWildCards = true;
object matchSoundsLike = false;
object matchAllWordForms = false;
object forward = true;
object format = false;
object matchKashida = false;
object matchDiacritics = false;
object matchAlefHamza = false;
object matchControl = false;
object read_only = false;
object visible = true;
object replace = false;
object wrap = Word.WdFindWrap.wdFindStop; ;
//execute find and replace
found = rngToSearch.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
if (!found)
{
rngToSearch = null;
}
return rngToSearch;
}
谢谢辛迪。我正在使用选择,因为如果我将使用范围,那么它将找到第一个搜索词并在其上循环。我有对象 forward = true;在我的搜索功能中。 (所以这种行为对我来说很奇怪)
private void button4_Click(object sender, RibbonControlEventArgs e)
{
string hyperlink = "https://Test";
string searchTerm =
@"<([1-5])[-^~]([0-9]{2})[-^~]([0-9]{1;6})/([0-9]{1;4})>"; // testing with 2-19-1023/47 2-19-1023/49
Word.Application app = Globals.ThisAddIn.Application;
Word.Range rngSel = app.Selection.Range;
Word.Range rngSearch = rngSel.Duplicate;
Word.Range rngFound = FindAndReplace(rngSearch, searchTerm, "");
while (rngFound != null)
{
string foundNr = rngFound.Text;
string hyperlinkNr = foundNr.Replace((char)30, (char)45);
rngFound.Hyperlinks.Add(rngFound, hyperlink + hyperlinkNr);
rngSearch.Start = rngFound.End;
rngSearch.End = rngSel.End;
rngFound = FindAndReplace(rngSearch, searchTerm, "");
File.AppendAllText(@"C:\install\CSharp\tulemus.txt", $"File name is: {rngFound.Text}" + Environment.NewLine);
}
我在我的测试文本文件中获得了无穷无尽的第一个可搜索字符串。你知道我该如何克服吗?
【问题讨论】:
标签: c# search ms-word selection office-interop