在VBA中将字符串数组转换为新字符串

时间:2017-05-29 06:40:58

标签: excel string vba excel-vba

我尝试创建一个VBA代码,将字符串(在数组中)转换为新字符串(也在数组中)。但是,我遇到了几乎完全相同的原始字符串的问题。例如。 “Power Partner”,“Power Partner OEM”。

有什么方法可以准确地转换它们吗?谢谢!

Private Function cvrt(orig As Variant) As Variant

    Dim orgVal As Variant, newVal As Variant, i As Integer

    cvrt = orig

    orgVal = Array("Central", "Clarke", "Power Partner", "Power Partner OEM")
    newVal = Array("Central Data", "Clarke Data", "Onsite Power Partner", "Onsite Energy OEM")

    For i = 0 To 3
        cvrt = Replace(cvrt, orgVal(i), newVal(i), vbTextCompare)
    Next i

End Function

2 个答案:

答案 0 :(得分:1)

如果您不想进入正则表达式的复杂世界,

  • 使用中间替换
  • 分两个阶段完成
  • 遵循在原始数组中放置“最大字符串优先”的规则。因此,dog应该 Power Partner OEM之前

Power Partner

请注意,中间数组不是必需的,您可以在任何地方使用Private Function cvrt(orig As Variant) As Variant Dim i As Long, orgVal, newVal, interm cvrt = orig orgVal = Array("Power Partner OEM", "Power Partner", "Central", "Clarke") interm = Array("xxx0", "xxx1", "xxx2", "xxx3") newVal = Array("Onsite Energy OEM", "Onsite Power Partner", "Central Data", "Clarke Data") For i = 0 To 3 cvrt = Replace(cvrt, orgVal(i), interm(i), vbTextCompare) Next i For i = 0 To 3 cvrt = Replace(cvrt, interm(i), newVal(i), vbTextCompare) Next i End Function 而不是"xxx" & i ...

答案 1 :(得分:1)

  

我的代码中的最后两个字符串出现问题,因为它们几乎相同。当我执行代码时," Power Partner OEM"这是不正确的,它变成了现场现场能源OEM" - kulapo

     

orig的值来自一个范围,在技术上列在orgVal中 - kulapo

最简单的方法是不使用Variants并使用Range,然后使用内嵌Range.replacexlWhole来避免误报匹配。

Private Function cvrt(orig As Range) As Range '<~~~~~
    Dim orgVal As Variant, newVal As Variant, i As Integer
    Dim rng As Range

    Set rng = orig

    orgVal = Array("Central", "Clarke", "Power Partner", "Power Partner OEM")
    newVal = Array("Central Data", "Clarke Data", "Onsite Power Partner", "Onsite Energy OEM")

    For i = 0 To 3
        rng.Replace What:=orgVal(i), Replacement:=newVal(i), LookAt:=xlWhole
    Next i

    Set orig = rng
End Function

截图

enter image description here

Sub Sample()
    Dim r As Range

    Set r = cvrt(Range("A1:A4"))
End Sub


Private Function cvrt(orig As Range) As Range
    Dim orgVal As Variant, newVal As Variant, i As Integer
    Dim rng As Range

    Set rng = orig

    orgVal = Array("Central", "Clarke", "Power Partner", "Power Partner OEM")
    newVal = Array("Central Data", "Clarke Data", "Onsite Power Partner", "Onsite Energy OEM")

    For i = 0 To 3
        rng.Replace What:=orgVal(i), Replacement:=newVal(i), LookAt:=xlWhole
    Next i

    Set orig = rng
End Function