我有一个问题是如何计算字符串或字符出现的次数。
例如: 有一个包含一些字符串的工作表:您好,我的名字是Ellen。我最喜欢的运动是篮球......
现在我想找到字符串"是"。正如你所看到的,字符串"是"显示两次。所以我得到的结果是2.
有谁可以帮助我? 谢谢大家。Excel.Range cells = ws.Cells;
match = cells.Find(
What: what,
After: Type.Missing,
LookIn: Excel.XlFindLookIn.xlFormulas,
LookAt: Excel.XlLookAt.xlPart,
SearchDirection: Excel.XlSearchDirection.xlNext
);
if (match == null)
log.Debug(xlDWorkBook.Name + "-" + xlSheet.Name + "找不到「" + what + "」");
else
{
log.Debug(xlDWorkBook.Name + "-" + xlSheet.Name + "共找到: " + count + "個「" + what + "」,並以「" + replacement + "」完成取代");
答案 0 :(得分:0)
我解决了! 我想以前我没有正确使用Find函数。 Find函数查找第一个匹配项,而不是所有匹配项。 How To: Programmatically Search for Text in Worksheet Ranges
int count = 0;
match = cells.Find(
What: what,
After: Type.Missing,
LookIn: Excel.XlFindLookIn.xlFormulas,
LookAt: Excel.XlLookAt.xlPart,
SearchDirection: Excel.XlSearchDirection.xlNext);
Excel.Range firstMatch = null;
while (match != null)
{
if (firstMatch == null)
{
firstMatch = match;
}
// If you didn't move to a new range, you are done.
else if (match.get_Address(Excel.XlReferenceStyle.xlA1)
== firstMatch.get_Address(Excel.XlReferenceStyle.xlA1))
{
break;
}
count++;
match = cells.FindNext(match);
}
cells.Replace(
what,
replacement,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByColumns,
false
);
log.Debug(xlDWorkBook.Name + "-" + xlSheet.Name + "共找到: " + count + "個「" + what + "」,並以「" + replacement + "」完成取代");
感谢每一位帮助:)