Quantcast
Channel: Excel Help Forum - Excel Programming / VBA / Macros
Viewing all articles
Browse latest Browse all 50057

Replacing the second instance of a string within another string.

$
0
0
I am trying to search though a column of data and replace all second instances of a specific string within a larger string. If the second instance isn't there then I don't perform a replacement. What I am finding is the replacement replaces everything in front of the string including the string. Obviously I am missing something with the syntax. Can someone look at the code and inform me what I am missing? Thank you in advance!

Code:

Sub test()
    Dim x As Long
    Dim last_R As Long
   
    last_R = Range("A65536").End(xlUp).Row
   
    For x = 1 To last_R
        my_var1 = InStr(1, Range("A" & x).Value, " xxx", vbTextCompare)
        my_var2 = InStr(my_var1 + 4, Range("A" & x).Value, " xxx", vbTextCompare)
       
        If my_var2 = 0 Then
            'do nothing
        Else
            my_var = Mid(Range("A" & x).Value, my_var2, 4)
           
            Range("A" & x).Value = Replace(Range("A" & x).Value, my_var, "", my_var2, 1, vbTextCompare)
        End If
    Next x
End Sub

The example workbook lists 5 possible situations that might come up. Only lines 1 and 2 should be changed from what should happen.
Attached Files

Viewing all articles
Browse latest Browse all 50057

Trending Articles