VBA 替换忽略 Column/Sheet 限制

VBA Replace is Ignoring Column/Sheet Restrictions

我正在尝试使用 VBA 作为 find/replace。目标是遍历 "Data_Pairs" sheet,其中包含 find/replace 的所有对,以及 find/replace 这些对 只有 A列和在工作簿的指定范围内sheet(不包括"Data_Pairs")。

出于某种原因,每个匹配值都会被替换,而不管它在哪一列。在 sheet 中索引超出定义范围的值也会被替换。

如有任何帮助,我们将不胜感激。

我正在使用以下代码:

Sub Replace_Names()

Dim row As Integer
Dim row2 As Integer
Dim sheet As Integer
Dim findThisValue As String
Dim replaceWithThisValue As String

For row = 1 To 10
  Worksheets("Data_Pairs").Activate
  findThisValue = Cells(row, "A").Value
  replaceWithThisValue = Cells(row, "B").Value
  For sheet = 2 To 10
    Worksheets(sheet).Columns("A").Replace What:= findThisValue, Replacement:=replaceWithThisValue     
  Next sheet
Next row
End Sub

举一个具体的例子来说明这个问题:如果Data_Pairs A1 = A 且Data_Pairs B1 = 1,则整个工作簿中的每个值1 都将替换为A。

您的 For ... Next 循环中有一个 Worksheets("Data_Pairs").Activate。这似乎表明该命令被调用的次数比它必须调用的次数多 9 倍。最好不要在 .Activate 上回复以提供 Cells.

的默认父级
Sub Replace_Names()
    Dim rw As long, ws As long
    Dim findThis As String, replaceWith  As String

    with Worksheets(1)
      For rw = 1 To 10
        findThis = .Cells(rw , "A").Value
        replaceWith = .Cells(rw , "B").Value
        For ws = 2 To 10  ' or sheets.count ?
          with Worksheets(ws)
            .Columns("A").Replace What:= findThis, Replacement:=replaceWith
          end with
        Next ws
      Next rw
    end with

End Sub

请参阅 How to avoid using Select in Excel VBA macros 了解更多关于远离 SelectActicate 的信息。

我观察到它在 Excel 2010 年按预期工作,与上面 Greg 和 chancea 的评论相呼应。

但是,我还观察到,如果您之前打开了“查找”对话框(例如,您正在执行一些手动 find/replace 操作)并将范围更改为 WORKBOOK,那么将会出现观察到的差异,如此处讨论:

http://www.ozgrid.com/forum/showthread.php?t=118754

这可能是一个疏忽,因为它似乎从未得到解决。虽然 Replace 对话框允许您指定工作簿与工作表,但没有相应的参数可以传递给 Replace 方法 (documentation)。

从 Ozgrid 线程实施 hack——出于某种原因,执行 .Find 方法似乎重置了它。这似乎有效:

Sub Replace_Names()

Dim row As Integer
Dim row2 As Integer
Dim sheet As Integer
Dim findThisValue As String
Dim replaceWithThisValue As String
Dim rng As Range

For row = 1 To 10
  Worksheets("Data_Pairs").Activate
  findThisValue = Cells(row, "A").Value
  replaceWithThisValue = Cells(row, "B").Value
  For sheet = 2 To 3
    Set rng = Worksheets(sheet).Range("A:A")
    rng.Find ("*")   '### HACK

    rng.Replace What:=findThisValue, Replacement:=replaceWithThisValue
  Next sheet
Next row
End Sub