首页 > 解决方案 > 比较 VBA 中的两个数字

问题描述

我正在尝试比较 2 个 3 位数字。这是我当前使用嵌套 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

而这只是其中的一小部分。另外,我还需要检查它们匹配的顺序。因此,无论是完全匹配,所有 3 位数字都以任意顺序匹配,或者 1 位或 2 位数字以任意顺序匹配。

问题是我有很多使用这种方法的 If 语句,因为我必须比较每个数字组合以检查 1 位、2 位、3 位等是否匹配。有没有更好的办法?

标签: excelvbanested-if

解决方案


可以简化为function一个简单的for循环

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

所以例如。digitMatch(023, 053)将返回2digitMatch(123, 321)将返回3


推荐阅读