在范围内查找多个字符串,对于每个查找,用文本填充相邻单元格

问题描述

我对创建 excel 宏非常陌生,目前,我正在努力在列中搜索一个字符串,然后在相邻的单元格中填充一个唯一的文本。我希望你能帮忙。 例如,我有 3 个名字,我想在相邻的单元格中调整它们,如下所示..(实际上我有大约 20 个)

| |一个 |乙|

| 1 |姓名 |所需格式|

| 2 |猫 | |

| 3 |狗 | |

| 4 |大象| |

想法是在范围(A2:A4)中寻找cat,如果找到,在相邻单元格中输入“17.Catiscool”,同样寻找Dog,如果找到,则在相邻单元格中输入“13.Dogisgood”以狗。

到目前为止,我的代码只是在 B3 中输入“13.Dogisgood”:

Sub To_be_renamed_as()
'Writing this to determine Correct Name format based on what we have from A3:A25
Dim oldRange As Range
Dim newRange As Range
Dim oldname As Object
Dim newname As String
'Our names start from A3 so I am going to start the range from A3
Set oldReportrange = Range("A3:A25")
Set newReportrange = Range("B3:B25")
For Each oldname In oldRange
    If oldname Like "dog" Then
    End If
    newname = ("13.dogisgood")
    oldname.Offset(0,1) = newname 
Next oldname
End Sub

我希望我能以一种方便的方式提出这个问题.. 非常感谢.. 提前致谢。

解决方法

在这种情况下,感觉 Select ... Case 语句效果最好。我已经编辑了您的代码以显示正在使用的代码

Sub To_be_renamed_as()
'Writing this to determine Correct Name format based on what we have from A3:A25
Dim oldRange As Range
Dim newRange As Range
Dim oldname As Object
Dim newname As String
'Our names start from A3 so I am going to start the range from A3
Set oldReportrange = Range("A3:A25")
Set newReportrange = Range("B3:B25")
For Each oldname In oldRange
    Select Case ucase(oldname.value) 'Make the input value all uppercase for easier comparison
        case "DOG"
            newname = "13.dogisgood"
        case "CAT"
            newname = "17.Catiscool"
        case else
            newname = ""
    end select
    oldname.Offset(0,1) = newname 
Next oldname
End Sub
,

请尝试下一个代码。它应该非常快,即使对于大范围,使用数组:

Sub To_be_renamed_as()
 Dim sh As Worksheet,arrRep,El,arrEl,rng As Range,arrRng,i As Long

 Set sh = ActiveSheet   'use here the sheet you need
 arrRep = Split("cat|17.Catiscool,dog|13.Dogisgood,elephant|ElephantIsBig",",") 'place here your conditions separated by "|"
 Set rng = sh.Range("A3:B25"): arrRng = rng.value   'set the range and put it in an array
 
 For Each El In arrRep                      'iterate between the arrRep elements
    arrEl = Split(El,"|")                  'split each element by "|"
    For i = 1 To UBound(arrRng)             'iterate between the arrRng rows
        If arrRng(i,1) Like arrEl(0) Then arrRng(i,2) = arrEl(1) 'when in the first column the search element is found
    Next i                                                         'the conditional string is passed in the second array column                                                         
 Next
 rng.value = arrRng  'Drop the processed array into the range,at once
End Sub

您可以根据需要添加 arrRep 多个条件(以“|”分隔)...

请测试并发送一些反馈。