【问题标题】:Issue with using WorksheetFunction.Substitute in combination with Offset将 WorksheetFunction.Substitute 与 Offset 结合使用时出现问题
【发布时间】:2019-06-02 14:03:14
【问题描述】:

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

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

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 引用硬编码字符串,它仍然以相同的方式失败。

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

【问题讨论】:

  • 替换列表是两个单元格的水平范围吗?
  • 可能:它是一个水平为两个,垂直为任意数字的列表。左边是原件,右边是替换件。
  • 敬畏那是一个完全不同的野兽。

标签: excel vba range offset substitution


【解决方案1】:

我认为您希望 Cells not Offset as 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

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

【讨论】:

  • 您可能希望查看您的多重替换的编辑。
  • 感谢斯科特。你能想出一个合理的方法来扩展它,让它只代替整个单词吗?例如我可能会安排将“Ed”替换为“Education”,而“Education”不会替换为“Educationucation”,我正在考虑基于 RegEx 的东西,但我想知道 Excel 是否还有其他技巧为此袖手旁观?
  • 顺便说一句,您的代码会更慢,因为它会迭代一个范围而不是一个数组。并且使用 Replace 将比工作表公式 Substitute 更快。
  • 啊,我知道你的方法更好了。我看到你花了一些时间来处理整个单词。单词可以以标点符号结尾,因此这里需要更复杂的方法。也许在标点符号周围插入空格然后在末尾重新标点符号的方法是一种解决方法。
【解决方案2】:

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

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 解决了我的问题时,我会将 Scott 的答案作为已接受的答案。

【讨论】:

    猜你喜欢
    • 2010-11-18
    • 2022-12-21
    • 2015-12-03
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多