0

尝试运行宏时出现以下错误:

Run-time error '1004':
Application-defined or object-defined error

这是宏:

Sub multiFindNReplace()
    Dim myList, myRange
    Set myList = Sheets("Receivable").Range("CN2:CO6") 'two column range where find/replace pairs are
    Set myRange = Sheets("Receivable").Range("A2:BQ1000") 'range to be searched
    For Each cel In myList.Columns(1).Cells
        myRange.Replace What:=cel.Value, Replacement:=cel.Offset(0, 1).Value, _
        LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
    Next cel
End Sub

当我单击“调试”时,以黄色突出显示的 3 行是:

myRange.Replace What:=cel.Value, Replacement:=cel.Offset(0, 1).Value, LookAt:=xlWhole, _
MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False

我能做些什么来解决这个问题?

4

1 回答 1

0

我怀疑第myList1 列中的值可能不存在于myRange

您可以在尝试替换不存在的内容之前对此进行测试,如果找不到则继续。见下文。(我删除了这些SearchFormat参数,因为它们似乎不适用于这里(默认值很好))

Option Explicit

Sub multiFindNReplace()

    Dim myList as Range, myRange as Range, cel as Range

    Set myList = Sheets("Receivable").Range("CN2:CO6") 'two column range where find/replace pairs are
    Set myRange = Sheets("Receivable").Range("A2:BQ1000") 'range to be searched

    For Each cel In myList.Columns(1).Cells

        Dim rngFound as Range
        Set rngFound = myRange.Find(cel.Value, LookAt:=xlWhole, MatchCase:=True)

        If not rngFound is Nothing Then 

            myRange.Replace What:=cel.Value, Replacement:=cel.Offset(0, 1).Value, _
                LookAt:=xlWhole, MatchCase:=True

        End If

    Next cel

End Sub
于 2016-04-01T17:10:20.030 回答