简体   繁体   English

在Excel中查找和替换列

[英]Find and Replace columns in excel

So I'm trying to write a VBA subroutine where we have 2 inputs 所以我试图编写一个VBA子例程,其中我们有2个输入

The first column is the current value and the second column is the value I want to replace it with. 第一列是当前值,第二列是我要替换为的值。

The issue I am running into is that it is not doing it for all of my worksheets just the one I am doing it on. 我遇到的问题是,它并没有在我所有的工作表上都执行,而只是在我正在执行的工作表上执行。

Where should I proceed? 我应该在哪里进行?

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

Have you looked at a search for "for each worksheet in workbook"? 您是否在寻找“针对工作簿中的每个工作表”的搜索? This might do it. 这可能会做到。

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

EDIT 编辑

Based on your comments, your code is not really at all going to address your need, since you want to programatically select your range. 根据您的评论,您的代码根本无法满足您的需求,因为您希望以编程方式选择范围。 This code will work if all of your "search" columns are column "B": 如果您所有的“搜索”列均为“ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM