Vba, find and replace but first occurrence only

yousufj567

New Member
Joined
Jul 6, 2017
Messages
3
Hi everyone,

Long time reader, first time poster.

Sheet1 contains 196 rows that contain the word "ToReplace" as part of larger string.
Sheet2 contains 196 rows that contain only the word "ToReplace" in column A and a unique value in column B.

I need to replace Sheet1 "ToReplace" with the unique value in column B.



Sheet1 Sheet2
[TABLE="width: 500"]
<tbody>[TR]
[TD]ToReplace[/TD]
[TD]ToReplace[/TD]
[TD]12345[/TD]
[/TR]
[TR]
[TD]ToReplace[/TD]
[TD]ToReplace[/TD]
[TD]56784[/TD]
[/TR]
[TR]
[TD]ToReplace[/TD]
[TD]ToReplace[/TD]
[TD]76543[/TD]
[/TR]
</tbody>[/TABLE]


This is the code i found online:

Sub myReplace()


Dim myDataSheet As Worksheet
Dim myReplaceSheet As Worksheet
Dim myLastRow As Long
Dim myRow As Long
Dim myFind As String
Dim myReplace As String

' Specify name of Data sheet
Set myDataSheet = Sheets("Sheet1")

' Specify name of Sheet with list of replacements
Set myReplaceSheet = Sheets("Sheet2")

' Assuming list of replacement start in column A on row 2, find last entry in list
myLastRow = myReplaceSheet.Cells(Rows.Count, "A").End(xlUp).Row

Application.ScreenUpdating = False

' Loop through all list of replacments
For myRow = 2 To myLastRow
' Get find and replace values (from columns A and B)
myFind = myReplaceSheet.Cells(myRow, "A")
myReplace = myReplaceSheet.Cells(myRow, "B")
' Start at top of data sheet and do replacements
myDataSheet.Activate
Range("A1").Select
' Ignore errors that result from finding no matches
On Error Resume Next
' Do all replacements on column A of data sheet
Columns("A:A").Replace What:=myFind, Replacement:=myReplace, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
' Reset error checking
On Error GoTo 0
Next myRow

Application.ScreenUpdating = True

MsgBox "Replacements complete!"

End Sub
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
Re: Help!! Vba, find and replace but first occurrence only

Hi everyone,

Long time reader, first time poster.

Sheet1 contains 196 rows that contain the word "ToReplace" as part of larger string.
Sheet2 contains 196 rows that contain only the word "ToReplace" in column A and a unique value in column B.

I need to replace Sheet1 "ToReplace" with the unique value in column B.
Try this:
Sheet1 should be the active sheet
Code:
Sub a1013082a()
Dim va, vb
Dim i As Long, j As Long
Dim va, vb

With Sheets("sheet2")
vb = .Range("A2", .Cells(Rows.count, "B").End(xlUp))
End With

va = Range("A2", Cells(Rows.count, "A").End(xlUp))
For i = 1 To UBound(va, 1)
    For j = 1 To UBound(vb, 1)
        If InStr(va(i, 1), vb(j, 1)) Then
         va(i, 1) = Replace(va(i, 1), vb(j, 1), vb(j, 2))
        End If
    Next
Next
Range("A2").Resize(UBound(va, 1), 1) = va

End Sub
 
Upvote 0
Re: Help!! Vba, find and replace but first occurrence only

Try this:
Sheet1 should be the active sheet
Code:
Sub a1013082a()
Dim va, vb
Dim i As Long, j As Long
Dim va, vb

With Sheets("sheet2")
vb = .Range("A2", .Cells(Rows.count, "B").End(xlUp))
End With

va = Range("A2", Cells(Rows.count, "A").End(xlUp))
For i = 1 To UBound(va, 1)
    For j = 1 To UBound(vb, 1)
        If InStr(va(i, 1), vb(j, 1)) Then
         va(i, 1) = Replace(va(i, 1), vb(j, 1), vb(j, 2))
        End If
    Next
Next
Range("A2").Resize(UBound(va, 1), 1) = va

End Sub


Hey, thanks for your feedback. However, it still changed it all instead of the first occurrence. Any other ideas? I really need this to work.
 
Upvote 0
Re: Help!! Vba, find and replace but first occurrence only

Hey, thanks for your feedback. However, it still changed it all instead of the first occurrence. Any other ideas? I really need this to work.

Oh, sorry, forget that you want to replace only the first one. Try this one:
Code:
Sub a1013082b()
Dim i As Long, j As Long
Dim va, vb

With Sheets("sheet2")
vb = .Range("A2", .Cells(Rows.count, "B").End(xlUp))
End With

va = Range("A2", Cells(Rows.count, "A").End(xlUp))
For j = 1 To UBound(vb, 1)
    For i = 1 To UBound(va, 1)
        If InStr(va(i, 1), vb(j, 1)) Then
         va(i, 1) = Replace(va(i, 1), vb(j, 1), vb(j, 2))
         Exit For
        End If
    Next
Next
Range("A2").Resize(UBound(va, 1), 1) = va

End Sub
 
Upvote 0
Re: Help!! Vba, find and replace but first occurrence only

Oh, sorry, forget that you want to replace only the first one. Try this one:
Code:
Sub a1013082b()
Dim i As Long, j As Long
Dim va, vb

With Sheets("sheet2")
vb = .Range("A2", .Cells(Rows.count, "B").End(xlUp))
End With

va = Range("A2", Cells(Rows.count, "A").End(xlUp))
For j = 1 To UBound(vb, 1)
    For i = 1 To UBound(va, 1)
        If InStr(va(i, 1), vb(j, 1)) Then
         va(i, 1) = Replace(va(i, 1), vb(j, 1), vb(j, 2))
         Exit For
        End If
    Next
Next
Range("A2").Resize(UBound(va, 1), 1) = va

End Sub


Geniuss!! it works!

Thank you so much. I really need this help.
 
Upvote 0
Hey, I have the same problem but a bit more complex. I want to only make the change once in the following code:

Dim Wbk As Workbook: Set Wbk = ThisWorkbook
Dim Wrd As New Word.Application
Dim Dict As Object
Dim RefList As Range, RefElem As Range
Dim Key
Dim wrdRng As Range
Dim WDoc As Document


Wrd.Visible = True

Set WDoc = Wrd.Documents.Open(filename:=sFileName, OpenAndRepair:=True) 'Modify as necessary.

Debug.Print sFileName

' Activar control de cambios en cada documento
With WDoc:
.TrackRevisions = False
WDoc.ActiveWindow.View.MarkupMode = wdBalloonRevisions
End With

'Assigns the columns that is going to have the original texts that need to be changed
Set Dict = CreateObject("Scripting.Dictionary")
Set RefList = Wbk.Sheets("Reemplazos").Range("B2:B50") 'Modify as necessary.


'Selects the column that´s one column to the right of the reference column
With Dict
For Each RefElem In RefList
If Not .Exists(RefElem) And Not IsEmpty(RefElem) Then
.Add RefElem.Value, RefElem.Offset(0, 1).Value
Debug.Print RefElem
End If
Next RefElem
End With

'Assigns the conditions and loops through each text to replace it
For Each Key In Dict
With WDoc.Content.FIND
Debug.Print Key
.Execute MatchAllWordForms:=False
.Execute Forward:=True
.Execute Wrap:=wdFindAsk
.Execute Format:=False
.Execute MatchCase:=False
.Execute MatchWildcards:=False
.Execute MatchSoundsLike:=False
.Execute wdReplaceAll
.Execute FindText:=Key, ReplaceWith:=Dict(Key), Replace:=2
End With
Next Key

The problem I have is with trackchanges. I have to active it due to the requirements of the automatization, but I´m finding myself with two words been changed twice. When I do it without trackchanges it works just fine.

This is an example of the problem I have. These are words that I´m replacing:

BuscarReemplazar
Trading - Energy Management Iberia - Strategic Short Term Manag.IbeEM Iberia - Strategic Short Term Mng. Ibe
Trading - Energy Management Iberia - Back Office Iberia (Operations)REVISAR
Trading - Energy Management Iberia - Back Office Iberia (Int. & Coord. Inf.)REVISAR
REVISARREVISAR
Responsable actividadREVISAR
Global Digital Solutions - Trading Digital Hub - AdoptionREVISAR
Global Digital Solutions - Trading Digital Hub - AdoptionDISTINTOS NIVELES
EM Iberia - Strategic Short Term Mng. IbeREVISAR
EM Iberia - EM Iberia - Credit & BO Ibe (Int. & Coord. Inf.)REVISAR
EM Iberia - Credit & BO Ibe - OperationsREVISAR
EM Iberia - Credit & BO Ibe - OperationsREVISAR
AFC - Administration Iberia - Accounting Iberia (Energetic Business)ADM Iberia - Accounting Ibe - Negocios Energéticos
AFC - Administration Iberia - Accounting IberiaBUSTED
ADM Iberia-Contabilidad-Negocios Energéticos-Balance de EnergíaREVISAR
AA2REVISAR
AA1REVISAR
Activity OwnerREVISAR


The problem I´m having is with these two words:
It changes the first one just fine, but then it changes the second one in the same words as if it wasn´t changed.
AFC - Administration Iberia - Accounting Iberia (Energetic Business)ADM Iberia - Accounting Ibe - Negocios Energéticos
AFC - Administration Iberia - Accounting IberiaBUSTED

This is the result I´m getting:
1652372976079.png

Without trackchanges, it does the change without any problems:
1652372862789.png


I need to get this result with trackchanges as true. But I´m unable to do it.

Any help will be greatly appreciated. Thanks a lot in advance.
 
Upvote 0
@Rafaelete
Your problem is different from the OP's problem in that it involves Word macro. I suggest you post a new thread. The new thread will attract more members to help.
 
Upvote 0

Forum statistics

Threads
1,223,893
Messages
6,175,244
Members
452,622
Latest member
Laura_PinksBTHFT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top