To create an Excel VBA script that prompts the user to select a file, performs a fuzzy match between all values in columns A and B, and outputs the results in a well-formatted manner on another sheet, follow these steps:
-
Enable the Microsoft Scripting Runtime Library: This library provides the Dictionary object, which is useful for storing and retrieving data efficiently.
- In the VBA editor, go to
Tools > References.
- Check the box for "Microsoft Scripting Runtime".
-
Implement the Levenshtein Distance Function: This function calculates the number of edits required to transform one string into another, serving as a measure of similarity.
Function LevenshteinDistance(ByVal s As String, ByVal t As String) As Integer
Dim d() As Integer
Dim m As Integer
Dim n As Integer
Dim i As Integer
Dim j As Integer
Dim cost As Integer
m = Len(s)
n = Len(t)
ReDim d(0 To m, 0 To n)
For i = 0 To m
d(i, 0) = i
Next i
For j = 0 To n
d(0, j) = j
Next j
For i = 1 To m
For j = 1 To n
If Mid(s, i, 1) = Mid(t, j, 1) Then
cost = 0
Else
cost = 1
End If
d(i, j) = Application.Min(d(i - 1, j) + 1, d(i, j - 1) + 1, d(i - 1, j - 1) + cost)
Next j
Next i
LevenshteinDistance = d(m, n)
End Function
-
Create the Main Subroutine: This subroutine will handle file selection, data processing, and result output.
Sub FuzzyMatchColumns()
Dim ws As Worksheet
Dim wsResults As Worksheet
Dim colA As Range
Dim colB As Range
Dim cellA As Range
Dim cellB As Range
Dim minDistance As Integer
Dim currentDistance As Integer
Dim bestMatch As String
Dim outputRow As Integer
Dim threshold As Integer
' Set the similarity threshold
threshold = 3 ' Adjust this value as needed
' Prompt user to select a file
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.Title = "Select an Excel File"
fd.Filters.Clear
fd.Filters.Add "Excel Files", "*.xls; *.xlsx; *.xlsm"
If fd.Show = -1 Then
Workbooks.Open fd.SelectedItems(1)
Else
MsgBox "No file selected. Exiting macro."
Exit Sub
End If
' Set the worksheet to the first sheet of the opened workbook
Set ws = ActiveWorkbook.Sheets(1)
' Create a new worksheet for results
Set wsResults = ActiveWorkbook.Sheets.Add
wsResults.Name = "Fuzzy Match Results"
' Set headers for the results sheet
wsResults.Cells(1, 1).Value = "Column A Value"
wsResults.Cells(1, 2).Value = "Best Match in Column B"
wsResults.Cells(1, 3).Value = "Levenshtein Distance"
wsResults.Cells(1, 4).Value = "Match Percentage"
' Define the ranges for columns A and B
Set colA = ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
Set colB = ws.Range("B2:B" & ws.Cells(ws.Rows.Count, "B").End(xlUp).Row)
outputRow = 2
' Loop through each cell in column A
For Each cellA In colA
minDistance = Len(cellA.Value) ' Initialize with the maximum possible distance
bestMatch = ""
' Loop through each cell in column B
For Each cellB In colB
currentDistance = LevenshteinDistance(LCase(cellA.Value), LCase(cellB.Value))
' Check if the current distance is less than the minimum found so far
If currentDistance < minDistance Then
minDistance = currentDistance
bestMatch = cellB.Value
End If
Next cellB
' Calculate match percentage
Dim maxLength As Integer
Dim matchPercentage As Double
maxLength = Application.Max(Len(cellA.Value), Len(bestMatch))
If maxLength > 0 Then
matchPercentage = (1 - minDistance / maxLength) * 100
Else
matchPercentage = 0
End If
' Output the result if the distance is within the threshold
If minDistance <= threshold Then
wsResults.Cells(outputRow, 1).Value = cellA.Value
wsResults.Cells(outputRow, 2).Value = bestMatch
wsResults.Cells(outputRow, 3).Value = minDistance
wsResults.Cells(outputRow, 4).Value = Format(matchPercentage, "0.00") & "%"
outputRow = outputRow + 1
End If
Next cellA
' Autofit columns for better readability
wsResults.Columns("A:D").AutoFit
MsgBox "Fuzzy matching complete. Results are in the 'Fuzzy Match Results' sheet."
End Sub