2017-05-29 12 views
0

我試圖創建一個將字符串(在數組中)轉換爲新字符串(也在數組中)的VBA代碼。但是,我遇到了幾乎相同的原始字符串問題。例如。 「電源合作伙伴」,「電源合作伙伴OEM」。將字符串數組轉換爲VBA中的新字符串

有什麼辦法可以將它們準確地轉換嗎?謝謝!

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 
+0

你得到了什麼問題?你傳遞給函數的'orig'的值是多少? –

+0

我的代碼中最後兩個字符串出現問題,因爲它們幾乎完全相同。當我執行代碼時,「電源合作伙伴OEM」的結果不正確,它變成了「現場能源OEM」 – kulapo

+0

您傳遞給函數的'orig'的值是多少? –

回答

1

如果你不想進入正則表達式的複雜世界,

  • 在使用中間更換
  • 按照把規則「最大的字符串第一個」做2個階段原始數組。因此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隨處可見,而不是interm(i) ...

1

我得到一個問題的最後兩個字符串在我的代碼,因爲他們幾乎相同。當我執行代碼時,「電源合作伙伴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 
+0

我也會嘗試這種方式,因爲它的簡單性。謝謝@SiddharthRout! – kulapo