在工作表

时间:2015-09-22 13:25:41

标签: excel vba excel-vba

我试图为Excel文件编写一些VBA,该文件在列标题中查找特定的短语/句子,并在找到它时更改该短语/句子。问题是,有时文件不会有我搜索的短语,并且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

当使用费(超额费用)"存在于工作表中,但如果它没有,那么我会收到一个错误,告诉我该对象不存在。

如果这句话不存在,有没有办法让这件事什么都不做?

2 个答案:

答案 0 :(得分:2)

最简单的方法是使用错误处理程序:

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

答案 1 :(得分:0)

以下是一些选择。前两个使用通配符但只替换1个实例。他们必须循环。第三个替换所有的byt取决于完全匹配(没有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