首页 > 解决方案 > 将 WorksheetFunction.Substitute 与 Offset 结合使用时出现问题

问题描述

我需要编写一个函数来根据在工作表中查找值对字符串进行多次替换。

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

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!工作表中的错误。

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

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

标签: excelvbarangeoffsetsubstitution

解决方案


我认为您希望 Cells not Offset 因为 Offset 将返回与父范围相同大小的范围。

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

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


推荐阅读