2015-02-06 37 views
4

我正在嘗試使用VBA進行查找/替換。目標是遍歷包含所有要查找/替換的對的「Data_Pairs」表單,並在工作簿的指定範圍的工作表中查找/替換列A中的只有只有不包括「Data_Pairs」)。VBA替換是忽略列/表限制

由於某些原因,每個匹配值都會被替換,而不管它所在的列是什麼。值也會被替換爲索引超出定義範圍的工作表中。

任何幫助將不勝感激。

我使用以下代碼:

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和B1 Data_Pairs = 1 1在整個工作簿的每一個值被替換與A.

+2

我只是跑這一點,它只是取代了值ColumnA我時,Excel 2013 – chancea 2015-02-06 21:19:59

+2

此代碼工作正常,我在Excel 2007 – Greg 2015-02-06 21:22:00

+1

讓我們把它3-爲3:此代碼在Excel 2010中爲我正確工作。 – 2015-02-06 21:28:24

回答

5

我觀察到Excel 2010中按預期工作,迴應Greg和上面的評論。

不過,我也注意到,如果你有以前打開查找對話框(例如,你正在做一些手工查找/替換操作)和改變範圍,工作簿時,則觀察到的差異會發生,因爲這裏討論:

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 
+1

這正是問題所在。我手動完成了一些CTRL + H替換整個工作簿作爲範圍。非常感謝! – LCG 2015-02-06 21:53:26

+1

乾杯。如另一個答案所示,這是明智的做法,以避免在繼續使用VBA時依賴選擇/激活方法。這裏是一個很好的入門話題:http:// stackoverflow。com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros – 2015-02-06 21:54:47

+1

好帖子David。 – brettdj 2015-02-07 01:29:43

1

您在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 

更多從SelectActicate越來越遠見How to avoid using Select in Excel VBA macros

+0

謝謝,這很有道理。 – LCG 2015-02-06 21:47:37