Thursday 26 April 2018

Excel Smart Find and Replace only specific characters


I want to change INT to INTERNATIONAL and NA to NATIONAL ASSEMBLY in whole excel workbook through an excel Macro or Find and Replace dialogue box. But when I run the macro or change it through Find and Replace dialogue box it also replace NA from CHINA last 2 characters and it became CHINATIONAL ASSEMBLY and INTERIOR to INTERNATIONALERIOR.


Now, I want that Excel should only smartly find the character NA in the workbook which is not included with any other character likewise character INT which is not attach to any other character.



Answer



If you go the VBA route, try using Regular Expressions


Here's a start


Sub ReplaceWithRE()
Dim re As Object 'RegExp
Dim rng As Range, cl As Range
Dim sh As Worksheet
Dim wb As Workbook
Dim sReplace As String
Dim aReplace(0 To 1, 0 To 1) As String
Dim i As Long

Set wb = ActiveWorkbook
Set re = CreateObject("vbscript.regexp") ' New RegExp
re.Global = True
re.IgnoreCase = False
re.MultiLine = True

' Load array of patterns and replacements
aReplace(0, 0) = "\bINT\b"
aReplace(0, 1) = "INTERNATIONAL"
aReplace(1, 0) = "\bNA\b"
aReplace(1, 1) = "NATIONAL ASSEMBLY"

For Each sh In wb.Worksheets
On Error Resume Next
Set rng = sh.UsedRange.SpecialCells(xlCellTypeConstants)
If Err.Number <> 0 Then
Err.Clear
Else
On Error GoTo 0
For Each cl In rng
sReplace = cl.Value
' Test each cell for each pattern, replace when found
For i = 0 To UBound(aReplace, 1)
re.Pattern = aReplace(i, 0)
If re.Test(sReplace) Then
sReplace = re.Replace(sReplace, aReplace(i, 1))
End If
Next
cl.Value = sReplace
Next
End If
Next


End Sub

No comments:

Post a Comment

Where does Skype save my contact&#39;s avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...