VBAreplace是忽略列/表限制
我正在尝试使用VBA进行查找/replace。 我们的目标是遍历一个“Data_Pairs”表单,其中包含所有要查找/replace的对,并仅在列A中查找/replace这些对,并且仅在工作簿中的指定范围的工作表中(不包括“Data_Pairs “)。
出于某种原因,每个匹配值都将被replace,而不pipe其中的哪一列。值也被replace为索引超出定义范围的工作表中。
任何帮助将不胜感激。
我使用下面的代码:
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都被replace为A.
我在Excel 2010中观察到了这种预期的效果,回应Greg和上面的评论。
但是,我也观察到,如果您以前打开了FIND对话框(例如,您正在执行一些手动查找/replace操作)并将范围更改为WORKBOOK,那么观察到的差异将会发生,如下所述:
http://www.ozgrid.com/forum/showthread.php?t=118754
这可能是一个疏忽,因为它似乎没有得到解决。 虽然“ Replace
对话框允许您指定“工作簿”与“工作表”,但没有相应的参数可以传递给“ Replace
方法( 文档 )。
实现从Ozgrid线程的破解 – 出于某种原因,执行.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
你有一个Worksheets("Data_Pairs").Activate
你的For ... Next
循环。 这似乎表明,该命令被称为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
请参阅如何避免使用在Excel VBAmacros中select以获取更多Select
和Acticate
。