2014-12-01 40 views
0

如何使用vba函數將替換函數從一個模式替換爲幾種模式?如何在vba中定義鏈接替換函數

想要的結果是:是否可以定義像sub2(cell,pat1,replacement 1,pat2,replacement 2,pat3,replacement 3)這樣的函數,而不是替代(cell,pattern,replacement,instancenumber)。 ..)?

謝謝。

回答

1

你可以使用ParamArrays來做到這一點,它允許你傳入儘可能多的參數。從這裏你解釋數值數組中執行自定義邏輯:

' patternReplacements are expected to have an even number of arguments. 
' The even param (0, 2, etc) would be the search text and the odd (1, 3, etc) the respective replacement text. 
Public Sub Substitute(ByVal cell As Range, ParamArray patternReplacements() As Variant) 
    Dim text As String 
    text = cell.Value 

    ' Perform text replacements. 
    ' Note - No logic here ensures an even number of arguments are passed, this could be easily added though. 
    Dim i As Integer 
    For i = 0 To UBound(patternReplacements) Step 2 
     text = Replace(text, patternReplacements(i), patternReplacements(i + 1)) 
    Next 

    cell.Value = text 
End Sub 

現在調用它,會是這個樣子:

Substitute Range("A1"), "find1", "replace1", "find2", "replace2", "find3", "replace3"