将 WorksheetFunction.Substitute 与 Offset 结合使用时出现问题

Issue with using WorksheetFunction.Substitute in combination with Offset

我需要编写一个函数,根据在 sheet.

中查找值,对字符串执行多次替换

我的意图是遍历 sheet 中的替换对列表,并为每次迭代调用工作簿函数 '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

如果你按原样使用代码,那么它就可以工作,因为如果我创建的函数中的第一个参数指向,它会将 "from" 替换为 "to"某处带有单词 "from" 的单元格。

但是,如果我注释掉对 temp1 或 temp2 的分配并取消注释其他行,我会得到一个#Value!作业出错sheet.

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

为什么会发生这种情况,我该如何解决?

我认为您希望单元格不偏移,因为偏移会 return 一个与父区域大小相同的范围。

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

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

最后我写的代码是这样的,虽然没有验证只有两列:

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

我将 Scott 的回答作为已接受的答案,因为他解决了我的问题。