Multiple research and replacement of strings in Excel
This is a VBA code for multiple research and replacement of strings in Excel selected sheet cells
My goal was to find and replace for bad character encoding in active sheet :
- é -> (replaced by) é
- è -> è
- ’ -> '
- î -> î
- ê -> ê
- Ã -> à
Common Functions required found in https://www.rondebruin.nl/win/s3/win002.htm
Sub Multi_FindReplace() adapted from https://www.mrexcel.com/board/threads/find-and-replace-multiple-values.1230258/
' Common Functions required for all routines
' Find the last row with data in sheet
Function LastRow(Sh As Worksheet)
On Error Resume Next
LastRow = Sh.Cells.Find(What:="*", _
After:=Sh.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
' Find the last col with data in sheet
Function LastCol(Sh As Worksheet)
On Error Resume Next
LastCol = Sh.Cells.Find(What:="*", _
After:=Sh.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
' Find and replace for bad character encoding in active sheet
' é -> é
' è -> è
' ’ -> '
' î -> î
' ê -> ê
' Ã -> à
Sub Multi_FindReplace()
Dim Sh As Worksheet
Dim LastR, LastC As Long
Dim Range As Range
Dim FindTips As Variant
Dim RplcTips As Variant
Dim y As Long
' Search
FindTips = Array("é", "è", "’", "î", "ê", "Ã")
' Replacement
RplcTips = Array("é", "è", "'", "î", "ê", "à")
' Select active sheet
ActiveSheet.Select
Set Sh = ActiveSheet
' Find the last row with data
LastR = LastRow(Sh)
' MsgBox LastR
' Find the last col with data
LastC = LastCol(Sh)
' MsgBox LastC
' Select Cells Range
Set Range = ActiveSheet.Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(LastR, LastC))
With Range
For y = LBound(FindTips) To UBound(FindTips)
Range.Replace What:=FindTips(y), Replacement:=RplcTips(y), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next y
End With
End Sub