VBA条件替换

问题描述 投票:0回答:1

我无法弄清楚自己该怎么做。我有两列,我想替换第二列中的数据,但仅当第1列的值与第2列中的值不同时。

第1栏熊猫熊蚂蚁等

第2列熊熊猫熊蚂蚁水母

我想要实现的是:

如果A1 <> B1,则将“Bear”替换为“哺乳动物”,依此类推。

先感谢您!

vba
1个回答
0
投票

这是一个例子,适当地改变。我对你的替换声明有点不确定。我已经编写了你已编写但我想知道你是否有一套替换名单?

以下代码遵循我的评论逻辑。

Sub test()

Dim wb As Workbook
Dim wsSource As Worksheet

Set wb = ThisWorkbook
Set wsSource = wb.Worksheets("Sheet4") 'change as appropriate

Dim lastRowColA As Long

lastRowColA = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row

Dim loopRange As Range

Set loopRange = wsSource.Range("A1:A" & lastRowColA)

Dim currCell As Range

For Each currCell In loopRange

    If currCell <> currCell.Offset(, 1) Then

        currCell.Offset(, 1) = Replace(currCell.Offset(, 1), "Bear", "Mammal")

    End If

Next currCell

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.