限制查找/替换区域

时间:2015-02-05 23:31:29

标签: excel vba excel-vba excel-2010

我有一个宏来清理原始输入电话号码,在我完成全局(工作簿)查找或替换的罕见情况之后,它通常效果很好,除了。如果我有脑屁&忘记从“工作簿”改回“工作表”模式它会猖獗,贪婪地提取' - '和& ''数据和数据类似于工作簿中所有工作表的公式,无论我想到我应用于它的限制。

如何正确约束它,所以我不需要每年花几个小时修复几次?

我现在拥有的:

Sheets("Data").Select  
Range("DataTbl[[Phone]:[Phone2]]").Select  ' DataTbl is 15 col x >800 row
Selection.Replace What:="  ", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:=")", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:="-", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:="(", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:=".", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

1 个答案:

答案 0 :(得分:3)

不再依赖.SelectSelection来定义您关注的领域。它可能在一些甚至大部分时间内起作用,但由于固有的模糊性,它只会导致最终的错误。

Dim r As Range
On Error Resume Next
Set r = Cells.Find(What:=vbNullString, LookIn:=xlFormulas, _
                 SearchOrder:=xlRows, LookAt:=xlPart, MatchCase:=False)
On Error GoTo 0
With Sheets("Data").Range("DataTbl[[Phone]:[Phone2]]")  ' DataTbl is 15 col x >800 row
    .Replace What:="  ", Replacement:=vbNullString, LookAt:=xlPart
    .Replace What:=" ", Replacement:=vbNullString, LookAt:=xlPart
    .Replace What:=")", Replacement:=vbNullString, LookAt:=xlPart
    .Replace What:="-", Replacement:=vbNullString, LookAt:=xlPart
    .Replace What:="(", Replacement:=vbNullString, LookAt:=xlPart
    .Replace What:=".", Replacement:=vbNullString, LookAt:=xlPart
End With

有关远离.Select的各种方法,请参阅How to avoid using Select in Excel VBA macros

编辑:在开头添加了四行代码,以重置“记住”'默认值为.Find个参数(例如在:工作表,而非在:工作簿中)。