如何一次替换多个字符串

时间:2019-05-07 06:05:15

标签: excel vba

我的行中包含不同的文本字符串,其中包含缩写词 例如A1 =“ Grw Option”,B1 =“ Grth Fund”,C3 =“ Growth Account”,而不是“ Growth Option”,“ Growth Fund”,“ Growth Account”。

我列出了不同的缩写,我需要用它们替换什么。

但是,大约有20个其他单词最多具有5种形式的缩写,我如何写出完整的VBA代码非常长。

我想知道是否有可能列出多个字符串,并仅使用一行代码即可将其替换为单个字符串。

我已经使用“查找并替换”功能来替换“增长”的每个缩写。

Sub ReplaceAbbr()

Dim ws As Worksheet

    ws.Cells.Replace What:="Grw", Replacement:="Growth", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    ws.Cells.Replace What:="Grth", Replacement:="Growth", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    ws.Cells.Replace What:="Grow", Replacement:="Growth", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

End Sub

我正在寻找一种更简短的替代方法来编写此脚本。

2 个答案:

答案 0 :(得分:1)

选项1:

Sub Test()

    Dim ws As Worksheet
    Dim arrReplace, arrReplacement

    Set ws = ThisWorkbook.Sheets("SheetName")

    arrReplace = Array("Grw", "Grth", "Grow")
    arrReplacement = Array("Growth", "Growth", "Growth")

    For i = LBound(arrReplace) To UBound(arrReplace)
        ws.Cells.Replace What:=arrReplace(i), Replacement:=arrReplacement(i), LookAt:=xlWhole, SearchOrder _
            :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
    Next i

End Sub

选项2:

Function Replacement(ws As Worksheet, Replace As String, Replacement As String)

    ws.Cells.Replace What:=Replace, Replacement:=Replacement, LookAt:=xlWhole, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

End Function
Private Sub Test2()

    Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("SheetName")

    Call Replacement(ws, "Grw", "Growth")

End Sub

在选项1中,您还可以在工作表中的某处将两个列表都列在其中,并将数组分配给这些列以使其更容易。

在选项2中,您还可以使用选项1中的循环。

答案 1 :(得分:0)

Option Explicit

Sub Test()

    Dim ws As Worksheet
    Dim arrReplace As Variant
    Dim strReplacement As String
    Dim i As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    arrReplace = Array("Grw", "Grth", "Grow", "ts", "tes", "tet")

    For i = LBound(arrReplace) To UBound(arrReplace)

        Select Case arrReplace(i)

            Case "Grw", "Grth", "Grow"
                strReplacement = "Growth"
            Case "ts", "tes", "tet"
                strReplacement = "Test"

        End Select

        ws.Cells.Replace What:=arrReplace(i), Replacement:=strReplacement, LookAt:=xlWhole, SearchOrder _
            :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    Next i

End Sub