简体   繁体   English

VBA Excel基于表值替换字符串

[英]Vba excel replacing string based on table values

I have code which replaces part of string in column A in sheet "Data" with new value written in Column B of sheet "Filter". 我有用新的值替换工作表“过滤器”的列B中写入的值的代码,该代码将工作表“数据”的A列中的字符串的一部分替换了。

Column A of sheet "Filter" has old values, and Column B has values after replacement, see picture: 工作表“过滤器”的A列具有旧值,而B列具有替换后的值,请参见图片:

在此处输入图片说明

I know how to replace for example "Griffith RV8" into "Griffith RV-8" but how can I do that replacement plus remove all characters in front of that replaced string? 我知道如何将“ Griffith RV8”替换为“ Griffith RV-8”,但是如何进行替换并删除替换字符串前面的所有字符?

Griffith RV8 = RV-8 格里菲斯RV8 = RV-8

Sub Substitutions()

Dim rngData     As Range
Dim rngLookup   As Range
Dim Lookup      As Range

With Sheets("Data")
    Set rngData = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
End With

With Sheets("Filter")
    Set rngLookup = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
End With

For Each Lookup In rngLookup
    If Lookup.Value <> "" Then
        rngData.Replace What:=Lookup.Value, _
                        Replacement:=Lookup.Offset(0, 1).Value, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        MatchCase:=False
    End If
Next Lookup

End Sub

You can use wildcards to replace parts of a string. 您可以使用通配符替换字符串的一部分。

Sub Example()

    Range("A1") = "Where in the World is Carmen Sandiego?"

    Range("A1").Replace "*Carmen", "Who is Micheal"

    Range("A3") = "Hello World! How are You?"

    Range("A3").Replace "!*", "? Can you hear me!?"

    Range("A5") = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    Range("A5").Replace "??H??", "fgHij"

    ' You can escape the wildcards using "\"
    Range("A7") = "? not escaped"

    Range("A8") = "WHO? WHO!"

    Range("A8").Replace "WHO?", "WHO ARE YOU?"

    Range("A10") = "? was escaped using a backslash \?"

    Range("A11") = "WHO? WHO!"

    Range("A11").Replace "WHO\?", "WHO ARE YOU?"

End Sub
rngData.Replace What:= "* " & Lookup.Value, _
                Replacement:=Lookup.Offset(0, 1).Value, _
                    LookAt:=xlPart, _
                    SearchOrder:=xlByRows, _
                    MatchCase:=False

will replace [some text here][space]Lookup.Value with Lookup.Offset(0, 1).Value 将用Lookup.Offset(0, 1).Value替换[some text here][space]Lookup.Value

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

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