从列表中查找和替换

时间:2019-06-21 14:36:22

标签: excel vba

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

这段代码是我在StackOverflow上看到的部分代码的一部分,但不允许我发表评论,以便原始作者可以帮助我。

在第.Add RefElem.Value, RefElem.Offset(0, 1).Value行给我一个错误457,我不知道为什么。

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个单词的列表替换为其他单词,空格,逗号或不包含任何内容。

2 个答案:

答案 0 :(得分:1)

出现错误是因为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 on the top of the code,因此它将自动检查所有变量的声明-例如key中没有声明。

答案 1 :(得分:0)

Sub FindReplace()

Dim findthis As Variant
Dim replacewith As Variant
Dim rng As range
Dim x As Long

findthis = Array("Value", "Value2", "Value3")
replacewith = Array("Difval", "Difval2", "Difval3")

Set rng = Sheets("Sheet1").range("A:A,C:C")

For x = LBound(findthis) To UBound(findthis)
rng.Cells.Replace what:=findthis(x), Replacement:=replacewith(x), _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
Next x

End Sub