excel - 将 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 引用硬编码字符串,它仍然以同样的方式失败。
为什么会发生这种情况,我该如何解决?
解决方案
我认为您希望 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
这将迭代两列范围的行,并将第一列中的项目替换为第二列中的值。
推荐阅读
- laravel - 在 TinyMCE 初始化时设置默认 HTML
- sql - 为 VIEW 创建存储过程
- python - 如何根据值将 CSV 文件拆分为 2 个单独的 CSV 文件
- git - 如何将最近的提交与之前的提交进行比较?
- ios - 未解决的标识符 NavigationButton 错误
- amazon-cloudformation - 在 CodeBuild 中使用自定义转换时运行 cloudformation 模板失败
- python - 适用于 Window 和 Linux 的 Python 虚拟环境 Shebang
- c++ - 我搜索了很多但仍然无法理解返回 const int * 或 const char * 的概念
- nginx - 在nginx中根据request_method设置proxy_pass
- postgresql - 如何从第 2 列的 BETWEEN(dates) 和第 1 列的 DUPLICATES 中找到 MAX(date)?