在工作表中search一个句子

我正在尝试为Excel文件编写一些VBA,在列标题中查找特定的短语/句子,如果发现它,则更改该短语/句子。 问题是,有时文件不会有我正在search的短语,并且VBA引发错误。 这是我的代码:

Dim srch As Range srch = Cells.Find(What:="Usage Charge (Overage Charges)", After:=ActiveCell, _ LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate If Not srch Is Nothing Then ActiveCell.FormulaR1C1 = "Usage Group Overage" End IF 

这在工作表中存在“使用费(超额费用)”的情况下可以正常工作,但是如果没有,则会收到一个错误,告诉我该对象不存在。

有没有办法让这个简单的做什么,如果这个短语不存在?

最简单的方法是使用error handling程序:

 Dim srch As Range On error goto ErrH srch = Cells.Find(What:="Usage Charge (Overage Charges)", After:=ActiveCell, _ LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate If Not srch Is Nothing Then ActiveCell.FormulaR1C1 = "Usage Group Overage" End IF Exit sub ErrH: ' Do nothing End sub 

这里有几个select。 前两个使用通配符,但只能replace1个实例。 他们将不得不循环。 第三个取代所有的取决于一个完全匹配(没有xlPart )。

 Sub optimal() Dim srch As Range, str As String, rpl As String str = "Usage Charge (Overage Charges)" rpl = "Usage Group Overage" With Worksheets("Sheet1") 'check if it exists using COUNTIF with silcards If CBool(Application.CountIf(.Rows(1), Chr(42) & str & Chr(42))) Then 'replace 1 occurance value directly .Cells(1, Application.Match(Chr(42) & str & Chr(42), .Rows(1), 0)) = rpl End If 'check if it exists using MATCH with silcards If Not IsError(Application.Match(Chr(42) & str & Chr(42), .Rows(1), 0)) Then 'replace 1 occurance value directly .Cells.Find(what:="Usage Charge (Overage Charges)", After:=ActiveCell, _ LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) = rpl End If 'use if "Usage Charge (Overage Charges)" is the entire cell content 'replaces all occurances .Rows(1).Replace what:=str, replacement:=rpl End With End Sub