使用宏在Excel中批量替换

时间:2016-03-26 23:40:11

标签: excel vba excel-vba

我找到了一段应该做我正在寻找的代码,但是我遇到了一个错误,我不知道如何解决。

代码如下,错误是编译错误:预期列表分隔符或

Sub multiFindandReplace()

Dim myList, myRange
Set myList = Sheets(“sheet1”).Range(“D1:E11”) ‘two column range with find/replace pairs
Set myRange = Sheets(“sheet1”).Range(“B1:B99”) ‘range to be searched and replace
For Each cel In myList.Columns(1).Cells
myRange.Replace What:=cel.Value, Replacement:=cel.Offset(0, 1).Value, LookAt:=xlWhole
Next cel

End Sub

对于宏和vba我真的很新,如果有一个明显的解决方案,那么道歉,但基本上我有一堆ID字符串(每个参与者约300个),我想用更简单的SubjectID替换。

我还在SubID旁边的一列中有每个ID字符串(见下文)。

理想情况下,我想运行一个宏,上面写着“用B1替换任何单元格A1的实例(即第一个ID字符串)”(即第一个SubID

ID String           Sub ID

R_RRdl3hwpEszOAO5     1

R_2DTiOiFDmERbIeP     2

R_1OHaghH1DCv8Rep     3

R_RwcKdPaKmX8De6Z     4

R_2rI62IyTK6rUHKu     5

2 个答案:

答案 0 :(得分:1)

您可以尝试以下Sub:

Sub ReplaceID()
    Dim maxRow As Integer
    maxRow = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
    Range("A1:A" & maxRow).Value = Range("B1:B" & maxRow).Value
End Sub

答案 1 :(得分:0)

您可以尝试以下三种宏之一

Option Explicit


Sub multiFindandReplace()

Dim myList As Range, myRange As Range

Set myList = Sheets("sheet1").Range("D1:E11") 'two column range with find/replace pairs
Set myRange = Sheets("sheet1").Range("B1:B99") 'range to be searched and replace

With myRange.SpecialCells(xlCellTypeConstants)
    With .Offset(, 1)
        .FormulaR1C1 = "=match(RC[-1]," & myList.Columns(1).Address(, , xlR1C1) & ",0)"
        .Value = .Value
    End With
    .FormulaR1C1 = "=index(" & myList.Columns(2).Address(, , xlR1C1) & ",RC[+1])"
    .Value = .Value
    .Offset(, 1).ClearContents
End With

End Sub


Sub multiFindandReplace2()

Dim myList As Range, myRange As Range, cell As Range, fnd As Range

Set myList = Sheets("sheet1").Range("D1:E11") 'two column range with find/replace pairs
Set myRange = Sheets("sheet1").Range("B1:B99") 'range to be searched and replace

For Each cell In myRange.SpecialCells(xlCellTypeConstants)
    cell.Value = myList.Cells(myList.Columns(1).Find(What:=cell.Value, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True).Row, 2)
Next cell
End Sub


Sub multiFindandReplace3()

Dim myList As Range, myRange As Range, cell As Range, fnd As Range

Set myList = Sheets("sheet1").Range("D1:E11") 'two column range with find/replace pairs
Set myRange = Sheets("sheet1").Range("B1:B99") 'range to be searched and replace

For Each cell In myRange.SpecialCells(xlCellTypeConstants)
    Set fnd = myList.Columns(1).Find(What:=cell.Value, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True)
    If Not fnd Is Nothing Then cell.Value = myList.Cells(fnd.Row, 2)
Next cell
End Sub

第一个是我测试中最快的一个,但是它使用了一个“帮助”列(myRange左边一个),你必须确保没有数据(否则很容易改变)

其他两个宏可能更快,然后通过在开头设置Application.ScreenUpdating=False,然后在结束前将其设置回Application.ScreenUpdating=True

最后一个与第二个相同,除了一点错误处理处理