在VBA代码中查找和替换文本会导致错误

时间:2017-12-12 12:01:31

标签: excel-vba vba excel

我有一个由Ron de Bruin创建的宏,我已修改它以替换我打开的文件中的文本。

我使用代码打开多个文件,获取数据,并将过滤后的列文本“To Be Paid”切换为“付费”。

我遇到的问题是,如果找不到文本,(没有此过滤器的记录)代码会停止并且不会完成。

是否有代码可用于继续/跳过此文件并转到下一个文件?

'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  ActiveSheet.ListObjects("List1").Range.AutoFilter Field:=10, Criteria1:= _
    "<>"
Columns("J:J").Select
Selection.Replace What:="to be paid", Replacement:="paid", LookAt:=xlPart _
    , SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
   'Remove the AutoFilter
    .AutoFilterMode = False
            End With
        End If
        'Close the workbook without saving
        mybook.Close savechanges:=True

1 个答案:

答案 0 :(得分:0)

如果有任何“需要付费”的单元格,你可以购买,如果他找到了,则可以进行替换。

Dim FoundRange As Range   

  ActiveSheet.ListObjects("List1").Range.AutoFilter Field:=10, Criteria1:= _
    "<>"
Columns("J:J").Select

Set FoundRange = Selection.Find(what:="to be paid", LookIn:=xlFormulas, lookat:=xlWhole)
if Not FoundRange is Nothing then
Selection.Replace What:="to be paid", Replacement:="paid", LookAt:=xlPart _
    , SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
End if

   'Remove the AutoFilter
    .AutoFilterMode = False
            End With
        End If
        'Close the workbook without saving
        mybook.Close savechanges:=True