在Excel中查找和替换列

时间:2017-11-20 16:35:07

标签: excel vba

所以我试图写一个VBA子程序,我们有2个输入

第一列是当前值,第二列是我想要替换它的值。

我遇到的问题是它并没有为我所有的工作表做这件事。

我应该在哪里继续?

Sub MultiFindNReplace()

    Dim Rng As Range
    Dim InputRng As Range, ReplaceRng As Range

    Set InputRng = Application.Selection
    Set InputRng = Application.InputBox("Original Range ", xTitleId, InputRng.Address, Type:=8)
    Set ReplaceRng = Application.InputBox("Replace Range :", xTitleId, Type:=8)

    Application.ScreenUpdating = False

    For Each Rng In ReplaceRng.Columns(1).Cells
        InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value
    Next

    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

您是否已查看了对工作簿中每个工作表的搜索"?这可能会这样做。

Sub MultiFindNReplace()

Dim Rng As Range
Dim InputRng As Range, ReplaceRng As Range

Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Original Range ", xTitleId, InputRng.Address, Type:=8)
Set ReplaceRng = Application.InputBox("Replace Range :", xTitleId, Type:=8)

Application.ScreenUpdating = False

For Each ws In ActiveWorkbook.Worksheets
    ws.Activate
    For Each Rng In ReplaceRng.Columns(1).Cells
         InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value
    Next
Next

Application.ScreenUpdating = True

End Sub

修改

根据您的评论,您的代码根本无法满足您的需求,因为您希望以编程方式选择范围。如果您的所有"搜索"列是" B":

Sub MultiFindNReplace()

Dim Rng As Range
Dim ReplaceRng As Range
Dim colNum as Int

colNum = 2 '2 = B

Application.ScreenUpdating = False

For Each ws In ActiveWorkbook.Worksheets
    ws.Activate
    'Sets the range from row 2 of the selected column to the last available row in the same column
    Set ReplaceRng = Range(Cells(2, colNum), Cells(Rows.Count, colNum).End(xlUp))
    For Each Rng In ReplaceRng.Columns(1).Cells
         InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value
    Next
Next

Application.ScreenUpdating = True

End Sub