简体   繁体   English

使用 VBA 代码一次查找和替换多个值

[英]Find and replace multiple values at once with VBA code

I have this VBA code to find and replace multiple values at once,i need one more feature in the code if the value is not replaced in the cell and remains same, content in the cell has to deleted and print as NO CHANGE.我有这个 VBA 代码可以一次查找和替换多个值,如果单元格中的值没有被替换并且保持不变,我需要代码中的另一个功能,单元格中的内容必须删除并打印为 NO CHANGE。 Could you please help to fix this code.你能帮忙修复这段代码吗?

Sheet 1第 1 张

List列表
Apple苹果
Mango芒果
grapes葡萄
Banana香蕉

Sheet 2工作表 2

List列表 Color颜色
Apple苹果 Red红色的
Mango芒果 yellow黄色的
grapes葡萄 black黑色的

Expected output预期产出

Sheet 1第 1 张

List列表
Red红色的
yellow黄色的
black黑色的
NO CHANGE没变化


Sub MultiFindNReplace()
'Updateby Extendoffice
Dim Rng As Range
Dim InputRng As Range, ReplaceRng As Range
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Original Range ", xTitleId, InputRng.Address, Type:=8)
Set ReplaceRng = Application.InputBox("Replace Range :", xTitleId, Type:=8)
Application.ScreenUpdating = False
For Each Rng In ReplaceRng.Columns(1).Cells
    InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value
Next
Application.ScreenUpdating = True
End Sub


I tried to print the status but none worked我试图打印状态但没有成功

You can add another loop that checks for a non-empty cell then replace the text if so.您可以添加另一个循环来检查非空单元格,如果是,则替换文本。 Something like -就像是 -

Sub MultiFindNReplace()
'Updateby Extendoffice
Dim Rng As Range
Dim InputRng As Range, ReplaceRng As Range

xTitleId = "KutoolsforExcel"

Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Original Range ", xTitleId, InputRng.Address, Type:=8)
Set ReplaceRng = Application.InputBox("Replace Range :", xTitleId, Type:=8)

Application.ScreenUpdating = False

For Each Rng In ReplaceRng.Columns(1).Cells
    InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value
Next

' New: Loop over remaining values and overwrite cells
For Each Rng in InputRng.Columns(1).Cells
  If IsEmpty(Rng.value) = false Then
    Rng.value = "NO CHANGE"
  End If
Next

Application.ScreenUpdating = True
End Sub

(I haven't tested this, but hopefully it gives you an idea on how to make it work.) (我还没有测试过这个,但希望它能给你一个关于如何让它工作的想法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM