【问题标题】:VBA Excel find and replace WITHOUT replacing items already replacedVBA Excel查找和替换而不替换已替换的项目
【发布时间】:2013-10-16 22:36:16
【问题描述】:

我正在寻找一个可以查找和替换数据的 excel 脚本,但是出于对一切的热爱,我不知道如何编写它。

情况:

A------------B------------C

猫-------狗-----香蕉

狗------鱼-----苹果

鱼------猫------橙色

因此,宏将查看 B 列中的单元格中的数据,然后查看 C 列中的相邻单元格,并将 A 列中该数据的所有实例替换为如果在 C 中找到的数据。所以结果将是:

A---------------B------------C

橙色-----狗-----香蕉

香蕉------鱼-----苹果

苹果--------猫-------橙色

但这还不是全部,我希望它不要更改 A 中已经更改过一次的单元格! (我正在尝试更改背景颜色)

有什么帮助吗?我完全不知所措。

编辑:

好的,我知道如何做简单的部分(替换),但我不知道如何不更改已经更改过一次的单元格。这是我的代码:

Sub multiFindNReplace()
    Dim myList, myRange
    Set myList = Sheets("sheet1").Range("A2:B3") 'two column range where find/replace pairs are
    Set myRange = Sheets("sheet1").Range("D2:D5") 'range to be searched
    For Each cel In myList.Columns(1).Cells
    myRange.Replace what:=cel.Value, replacement:=cel.Offset(0, 1).Value, ReplaceFormat:=True
    Next cel
End Sub

据我所知,ReplaceFormat:=True 什么都不做;/所以已经被替换过的项目仍然被替换!有没有办法以某种方式完成这项工作?

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    以下是使用您的建议和颜色作为一次性限制器的答案:

    Sub Replace_Once()
    
    'Find last row using last cell in Column B
    LastRow = Range("B" & Rows.Count).End(xlUp).Row
    
    'Clear colors in Column A
    Range("A1:A" & LastRow).Interior.ColorIndex = xlNone
    
    'Look at each cell in Column B one at a time (Cel is a variable)
    For Each Cel In Range("B1:B" & LastRow)
        'Compare the cell in Column B with the Value in Column A one at a time (C is a variable)
        For Each C In Range("A1:A" & LastRow)
            'Check if the Cell in Column A matches the Cell in Column B and sees if the color has changed.
            If C.Value = Cel.Value And C.Interior.Color <> RGB(200, 200, 200) Then
                'Colors the cell
                C.Interior.Color = RGB(200, 200, 200)
                'Updates the value in Column A with the cell to the right of the Cell in Column B
                C.Value = Cel.Offset(0, 1).Value
            End If
        Next
    Next
    
    'Uncomment the line below to remove color again
    'Range("A1:A" & LastRow).Interior.ColorIndex = xlNone
    
    End Sub
    

    【讨论】:

    • 感谢您的回答!我还是 VBA 的新手,所以我无法理解这段代码。正在更改哪一行以及正在使用哪些行来更改该行?
    • 现在代码清晰了吗?您也可以通过反复按 F8 遍历每一行来测试它,然后观察发生了什么。
    • 这真是太棒了!由于某种原因,范围(“B1:B”和 LastRow)似乎不起作用。当我将它更改为特定范围时,它就像一个魅力,但当它使用 LastRow 时,它似乎不起作用。编辑:想通了为什么,当 B 列与 A 的长度不同时,它不会将宏应用于 A 列中比 B 长的部分。是否有可能绕过这个?
    • @LeMarcin 当您使用F8 键单步执行代码时,分配后lastRow 的值是多少?
    • 不管 B 列的长度是多少(在我的测试中是 264,A 列是 3650 [分配重复项]) = Range("B" & Rows.Count).End(xlUp).Row 使用 A 而不是 B
    猜你喜欢
    • 2013-07-15
    • 2014-10-12
    • 2018-04-11
    • 2016-06-10
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多