简体   繁体   English

多个查找和替换

[英]Multiple Find & Replace

I've trawled this site but not found anything exact for my issue.我已经浏览了这个网站,但没有找到任何适合我的问题的内容。

I have an excel file (Sheet1) containing various foreign characters (eg. "ä" or "Ö") within multiple columns and rows (basically the entire sheet).我有一个 excel 文件(Sheet1),其中包含多个列和行(基本上是整个工作表)中的各种外来字符(例如“ä”或“Ö”)。

In Sheet2 I have a list/table (Columns A & B) of these characters (A) and what they need to be replaced with (B).在 Sheet2 中,我有这些字符 (A) 的列表/表格(A 列和 B 列)以及它们需要替换为 (B) 的内容。

I would like a VBA code to search for all of these characters in Sheet1 and replace them all with the corresponding alternative.我想要一个 VBA 代码来搜索 Sheet1 中的所有这些字符,并将它们全部替换为相应的替代项。

Any help would be amazing.任何帮助将是惊人的。

Thanks,谢谢,

Ross, your solution almost did the trick.罗斯,你的解决方案几乎成功了。 You can simplify it by using:您可以使用以下方法简化它:

Sub ReplaceChar()
    Dim Sh1 As Worksheet
    Dim Sh2 As Worksheet
    Dim cel As Range

    Set Sh1 = Sheets(1)
    Set Sh2 = Sheets(2)

    For Each cel In Sh2.Columns(1).SpecialCells(2)
        With Sh1.Cells
            .Replace What:=cel, Replacement:=cel.Offset(, 1), MatchCase:=True
        End With
    Next
End Sub

Sheet1 and Sheet2 before running the macro:运行宏之前的 Sheet1 和 Sheet2:

在此处输入图片说明

在此处输入图片说明

...and here's Sheet1 after running the code: ...这是运行代码后的 Sheet1:

在此处输入图片说明

Experience has shown me that upper & lower case chars are treated the same when using find and replace.经验告诉我,在使用查找和替换时,大小写字符的处理方式相同。

The below sample uses column Q as the character to find and column R as the replacement.下面的示例使用 Q 列作为查找字符,R 列作为替换字符。 The code does the find replace for cells in column A该代码对 A 列中的单元格进行查找替换

Sub Using_Replace()
    Dim LstRw As Long, rng As Range, c As Range

    LstRw = Cells(Rows.Count, "Q").End(xlUp).Row
    Set rng = Range("Q1:Q" & LstRw)

    For Each c In rng.Cells

        Range("A:A").Replace what:=c, Replacement:=c.Offset(, 1), _
                             LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                             SearchFormat:=False, ReplaceFormat:=False
    Next c

End Sub

在此处输入图片说明

When you test out the code you will notice the find/replace does not notice the difference between the characters in Q6 & Q15.当您测试代码时,您会注意到查找/替换没有注意到 Q6 和 Q15 中的字符之间的差异。

But if you loop through each cell, the differences are recognized.但是,如果您遍历每个单元格,就会识别出差异。

- ——

Sub Using_LikeLoop()
    Dim LstRw As Long, rng As Range, c As Range
    Dim frNg As Range, f As Range

    LstRw = Cells(Rows.Count, "Q").End(xlUp).Row
    Set rng = Range("Q1:Q" & LstRw)
    Set frNg = Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)

    For Each c In rng.Cells

        For Each f In frNg.Cells

            If f Like "*" & c & "*" Then f = Replace(f, c, c.Offset(, 1))

        Next f

    Next c

End Sub

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

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