excel - 从列表中查找和替换
问题描述
尝试在两个特定列中查找和替换多个单词。
这段代码部分来自我在 StackOverflow 上看到的几个代码,但不允许我发表评论,以便原作者可以帮助我。
给我一个错误457,.Add RefElem.Value, RefElem.Offset(0, 1).Value
我不知道为什么。
Sub Cambios()
Dim Wbk As Workbook: Set Wbk = ThisWorkbook
Dim Wsht As Worksheet: Set Wsht = Wbk.Sheets("Sheet1") 'Modify as needed.
Dim Dict As Object
Dim RefList As Range, RefElem As Range
Dim TargetRng As Range
Set Dict = CreateObject("Scripting.Dictionary")
Set RefList = Wsht.Range("L2:L93") 'Modify as needed.
Set TargetRng = Union(Wsht.Range("C1:C50"), Wsht.Range("F2:F345")) 'Modify as needed.
With Dict
For Each RefElem In RefList
If Not .Exists(RefElem) And Not RefElem Is Nothing Then
'ERROR HERE
.Add RefElem.Value, RefElem.Offset(0, 1).Value
End If
Next RefElem
End With
For Each Key In Dict
With TargetRng
.Replace What:=Key, Replacement:=Dict(Key)
End With
Next Key
Set Dict = Nothing
End Sub
它旨在将 92 个单词的列表替换为其他单词、空格、逗号或任何内容。
解决方案
错误来了,因为Add RefElem.Value
向字典中添加了一个空字符串,这在设计上是不合适的。问题出在条件检查中:
If Not .Exists(RefElem) And Not RefElem Is Nothing Then
这部分永远不可能是 TRUE - RefElem Is Nothing
,因为RefElem
它是一个范围单元格,因此它总是“某物”。
由于代码很可能试图检查单元格中是否存在值,因此这是一个很好的解决方法:
If (Not .exists(RefElem.Value2)) And Trim(RefElem) <> "" Then
另外 - 考虑Option Explicit
在代码的顶部写,因此它会自动检查所有变量的声明 - 例如答案key
中没有声明。
推荐阅读
- mongodb - 如何在mongodb的对象数组中查找数据
- javascript - 无法在节点 js 的 pm2 实例上更改 config/name.json 文件
- python - 如何使用 OpenCV 去除图像上的蓝色背景色?
- robotics - 是否可以使用 G1ANT Studio 自动化 Outlook?
- c++ - C ++如何仅实现多继承类的一个构造函数
- python-3.x - 无法从我的测试文件夹中导入模块服务器
- swift - Swift 中的“存在类型”是什么意思?
- sql - 在一个表中显示两个临时表数据
- android - Kotlin 从字符串中解析双精度
- mule4 - Mule 4 不支持将代码 Mule 3 迁移到 Mule 4 和“rest-router”