Search code examples
excelvbanested-if

Comparing 2 Numbers in VBA


I'm trying to compare 2 3-digit numbers. This is my current code using nested Ifs

If Mid(Num1, 1, 1) = Mid(Num2, 1, 1) Then  
'Check first number against first number

If Mid(Num1, 2, 1) = Mid(Num2, 2, 1) Then 
 'Check second number against second number


   If Mid(Num1, 3, 1) = Mid(Num2, 3, 1) Then  
    'Check third number against third number 

        Digits = 3

    Else

        Digits = 2

    End If

And this is just one small part of it. Also, I need to check the order in which they match as well. So whether it's an exact match, all 3 digits match in any order, or if 1 or 2 digits match in any order.

The problem is I have a lot of If statements using this method as I have to compare every combination of digits to check for a 1 digit, 2 digit, 3 digit, etc, match. Is there a better way?


Solution

  • Can be simplified to a function with a simple for loop

    Private Function digitMatch(ByVal num1 as String, ByVal num2 as String) As Byte
     ' num1 and num2 are strings, because of presumption they can start with 0
     ' (i.e. 042 is valid 3 digit number format, otherwise they can be integers as well)
    
      Dim i As Byte
      Dim matches As Byte: matches = 0
    
      For i = 1 To Len(num1)
         If InStr(1, num2, Mid(num1, i, 1)) <> 0 Then
            matches = matches + 1
         End If
      Next i
    
      digitMatch = matches
    
    End Function
    

    so eg. digitMatch(023, 053) would return 2 or digitMatch(123, 321) would return 3