1

I'm trying to replace some words with others in the same column using VBA. Currently, I'm able to replace single word but I want to replace multiple words at the same time.

Below is code-

Sub replce()
Worksheets("Sheet1").Columns("C").Replace _
 What:="Ryan Group", Replacement:="COS", _
 SearchOrder:=xlByColumns, MatchCase:=True
End Sub

But, I want to replace like

Sub replce()
Worksheets("Sheet1").Columns("C").Replace _
What:= "Ryan Group, Zyan Group, Wayn Group", Replacement:="COS, TAN, SIN"
 SearchOrder:=xlByColumns, MatchCase:=True
End Sub

How can I replace the multiple words? can I implement this by using any other VBA code? Please help. Thanks in advance. Be safe!

4
  • replace them one by one Commented Jul 22, 2020 at 21:07
  • 2
    Use two arrays, one with the original words, and one with the replacement words, and a loop. Commented Jul 22, 2020 at 21:11
  • @BigBen yeah, I thought of using the loop. But I'm new in this so, I'm don't really know how to use the loop. Commented Jul 22, 2020 at 21:19
  • I found too many VB codes but none of them is working for me, this one is simple and working without any error but I just want to use the loop in it. I dont know how to use array and loop Commented Jul 22, 2020 at 21:31

2 Answers 2

4

Use two arrays and a loop:

Sub replce()
    Dim fromList() As Variant
    Dim toList() As Variant
    
    fromList = Array("Ryan Group", "Zyan Group", "Wayn Group")
    toList = Array("COS", "TAN", "SIN")
    
    Dim i As Long
    For i = LBound(fromList) To UBound(fromList)
        Worksheets("Sheet1").Columns("C").Replace _
            What:=fromList(i), Replacement:=toList(i), _
            SearchOrder:=xlByColumns, MatchCase:=True
    Next

End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

In my opinion you could try the below code:

Sub replce()

    Dim strWhat As String, strRep As String
    Dim arrWhat As Variant, arrRep As Variant
    Dim i As Long
    
    strWhat = "Ryan Group, Zyan Group, Wayn Group"
    strRep = "COS, TAN, SIN"
    
    With ThisWorkbook.Worksheets("Sheet1").Columns("C")
    
        arrWhat = Split(strWhat, ",")
        arrRep = Split(strRep, ",")
        
        For i = LBound(arrWhat) To UBound(arrWhat)
            .Replace What:=Trim(arrWhat(i)), Replacement:=Trim(arrRep(i)), SearchOrder:=xlByColumns, MatchCase:=True
        Next i
        
    End With
    
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.