UDF制作一种替代数组函数

时间:2015-10-02 21:29:58

标签: excel vba function substitution udf

我正在尝试创建一个不仅用一个文本替换另一个文本的函数, 但是用另一个横向值集替换一个范围内的一组值。

我有这个:

Public Function SubstituteRange(RangeWithText As Range, TwoColumnMatrix As Range) As String
Dim Text As String
Text = "/" & RangeWithText.Value & "/"
'as example st like this: "/" & "1/2/3/4/5/6/7/8" & "/" = "/1/2/3/4/5/6/7/8/"
Dim SearchForRange As Range
Set SearchForRange = TwoColumnMatrix.Columns(1)
'let us say "A1:A4" with /2/ /3/ /4/ /5/ in each cell    
Dim ReplaceWithRange As Range
Set ReplaceWithRange = TwoColumnMatrix.Columns(2)
'let us say "B1:B4" with /9/ /10/ /11/ /12/ in each cell
Dim i As Integer
SubstituteRange = Text
For i = 1 To SearchForRange.Rows.Count '4 rows
SubstituteRange = Application.WorksheetFunction.Substitute(SubstituteRange, _
SearchForRange.Item(i), ReplaceWithRange.Item(i))
Next i
End Function

但这会返回“#Value!”错误, 有人可以帮我这个吗? 我希望从这个例子中获得类似“/ 1/9/10/10/12/6/7/8 /”的内容,但我没有得到它。 提前谢谢你。

2 个答案:

答案 0 :(得分:1)

Function MultiReplace(v, rng)
    Dim rw As Range, rv
    rv = "/" & v & "/"
    For Each rw In rng.Rows
        rv = Replace(rv, rw.Cells(1).Value, rw.Cells(2).Value)
    Next rw
    MultiReplace = rv
End Function

答案 1 :(得分:0)

尝试将替换语句更改为此(已测试):

SubstituteRange = Application.Substitute(SubstituteRange, _
SearchForRange.cells(i).Text, ReplaceWithRange.Cells(i).Text)