将WorksheetFunction.Substitute与Offset结合使用的问题

时间:2019-01-07 21:44:23

标签: excel vba range offset substitution

我需要基于在工作表中查找值,编写一个函数以对字符串进行大量替换。

我的意图是遍历工作表中的替换对列表,并为每次迭代调用工作簿函数“ substitute”。

Function multiSub(original As Range, replaceList As Range)
Dim temp1 As String
Dim temp2 As String
Dim temp3 As String

  '  temp1 = replaceList.Offset(0, 0).Value
  '  temp2 = replaceList.Offset(0, 1).Value
  temp1 = "from"
  temp2 = "to"
    multiSub = Application.WorksheetFunction.Substitute(original, temp1, temp2)
End Function

如果您按原样使用代码,那么它将起作用,因为如果我创建的函数中的第一个参数指向带有单词“”的单元格,它将用单词“ to”替换单词“ from”。来自“在某处。

但是,如果我注释掉temp1或temp2的分配并取消注释其他行,则得到#Value!工作表中的错误。

有趣的是,即使我为这些范围偏移量之一分配了一个不相关的变量(例如temp3),并将temp1和temp2都引用为硬编码字符串,它仍然会以相同的方式失败。

为什么会这样,我该如何解决?

2 个答案:

答案 0 :(得分:1)

我认为您希望单元格不偏移,因为偏移将返回与父范围相同的范围。

Function multiSub(original As Range, replaceList As Range)
Dim temp1 As String
Dim temp2 As String
If replaceList.Rows.Count <> 1 Or replaceList.Columns.Count <> 2 Then
    multiSub = "error"
End If

  temp1 = replaceList.Cells(1, 1).Value
  temp2 = replaceList.Cells(1, 2).Value


    multiSub = Replace(original, temp1, temp2)
End Function

要进行多次替换:

Function multiSub(original As Range, replaceList As Range)

If replaceList.Columns.Count <> 2 Then
    multiSub = "error"
End If

Dim temp1 As Variant
 temp1 = replaceList

Dim i As Long
For i = LBound(temp1, 1) To UBound(temp1, 1)
    multiSub = Application.Trim(Replace(" " & original & " ", " " & temp1(i, 1) & " ", " " & temp1(i, 2) & " "))
Next i
End Function

这将迭代两列范围内的行,并将第一列中的项目替换为第二列中的值。

答案 1 :(得分:0)

我最后编写的代码是这样的,尽管它不能验证只有两列:

Function multiSub(original As Range, replaceList As Range)
Dim temp1 As String
Dim temp2 As String
Dim row As Range

multiSub = original
    For Each row In replaceList.Rows
        multiSub = Application.WorksheetFunction.Substitute(multiSub, row.Cells(1, 1), row.Cells(1, 2))
    Next row
End Function

当斯科特解决我的问题时,我将把他的答案留为公认的答案。