首页 > 解决方案 > 从列表中查找和替换

问题描述

尝试在两个特定列中查找和替换多个单词。

这段代码部分来自我在 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 个单词的列表替换为其他单词、空格、逗号或任何内容。

标签: excelvba

解决方案


错误来了,因为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中没有声明。


推荐阅读