Check if Two words are Anagram
Anagrams are two or more different words with same combination of letters.
For example: now, won, own
How do we compare & verify if the two words are Anagrams or not?
We can follow different logic, as discussed in here.
VBA code to Check for Anagram
Either we can take each word from first letter and check if it is present in second word also.
Or we can arrange the second word to get first word. If we are not able to form first word then it is not anagram. Or we can arrange each letter in both words in alphabetical order.
Then verify each letter if they both are same.
Here is one simple VBA code to check whether two words are anagram or not?
Sub Check_If_Anagram() Dim str1 As String, str2 As String Dim c1 As String, c2 As String Dim i As Double, j As Double Dim chrFound As Boolean str1 = "solve" str2 = "loves" str1 = VBA.Trim(VBA.UCase(str1)) str2 = VBA.Trim(VBA.UCase(str2)) If VBA.Len(str1) <> VBA.Len(str2) Then MsgBox "Number of Letters are not same - Both words should have same length" Exit Sub End If For i = 1 To VBA.Len(str1) c1 = VBA.Mid(str1, i, 1) chrFound = False For j = 1 To VBA.Len(str2) c2 = VBA.Mid(str2, j, 1) If c1 = c2 Then chrFound = True Exit For End If Next j If chrFound = False Then MsgBox "Not Anagram - Letter " & c1 & " is missing" Exit For End If Next i If chrFound = True Then MsgBox str1 & " : " & str2 & " are Anagrams" End If End Sub
This code actually followed the first technique. i.e., compare each word.
Remember to input words of same length. if the length does not match, then this macro will not perform anagram check.