VBA在每个循环中查找和替换变量?

时间:2014-11-27 15:23:42

标签: excel vba

我有一张包含27,000条记录的CSV,其中一些姓氏上有括号和文字,例如Harvey(MD5),我已设法使用它,所以它会在针对单个目标时执行单元格删除括号内的文本和括号本身,但是当我尝试循环它时,我得到一个[RUNTIME ERROR 5] - 无效的过程调用或参数....

这是我的循环

    Sub test()
Application.ScreenUpdating = False
Dim myCell As Range
Dim myRange As Range
Dim cellvalue As String

Set myRange = Range("D1:D27168")


For Each myCell In myRange

cellvalue = myCell.Value

openingParen = InStr(cellvalue, "(")
closingParen = InStr(cellvalue, ")")
enclosedValue = Mid(cellvalue, openingParen + 1, closingParen - openingParen - 1)

         Cells.Find(What:=enclosedValue, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=False).Activate
    ActiveCell.Replace What:=enclosedValue, Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

Next myCell
Application.ScreenUpdating = True
End Sub

有什么我做错了,我删除了括号查找并替换代码以保持简短。

感觉像是小姐

1 个答案:

答案 0 :(得分:0)

由于openingParenclosingParen值,您可能会收到错误消息。如果Mid获取错误的整数输入(例如Mid("text", 1, 1 - 3)Mid("text", -10, 5)),则会失败并显示错误5.
我建议在调用{{1}之前测试InStr结果和/或添加Error Handling,类似(伪代码,未测试):

Mid