在VBA中比较2个数字

时间:2019-03-13 16:11:06

标签: excel vba nested-if

我正在尝试比较2个3位数字。这是我当前使用嵌套Ifs的代码

RdYlBu

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

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

3 个答案:

答案 0 :(得分:1)

可以通过简单的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)将返回2   或digitMatch(123, 321)会返回3

答案 1 :(得分:1)

在我的答案中,我返回匹配的数字,因此您可以检查是否有数字以及哪些数字。另外,它可以使用任意数量的数字。

Public Function CheckForMatch(ByVal curNum As String, ByVal winNumber As String) As String

    Dim i As Long, j As Long

     Dim hit As String
     hit = vbNullString

     For i = 1 To Len(curNum)
        j = InStr(1, winNumber, Mid(curNum, i, 1), vbTextCompare)
        If j > 0 Then
            hit = hit & Mid(curNum, i, 1)
        End If
    Next i

    CheckForMatch = hit
End Function

Public Sub Test()

    Dim check As String

    check = CheckForMatch("75214", "13672")

    If Len(check) > 0 Then
        Debug.Print "Numbers " & check & " are a match."
        ' 721
    Else
        Debug.Print "No match. Sorry."
    End If

End Sub

注意:此处InStr()的使用是受Rawplus在我面前给出的答案的启发。

答案 2 :(得分:0)

尝试一下(仅当'curNum'和'WinningNumber'均为3位数字时,它才能正常工作):

'straight match
If curNum = WinningNumber Then
    M = 3
    s = 3
'matched the first 2 straight
ElseIf InStr(1, WinningNumber, Left(curNum, 2)) > 0 Then
    M = 2
    s = 2
    If InStr(1, WinningNumber, Right(curNum, 1)) > 0 Then M = M + 1
'matched the last 2 straight
ElseIf InStr(2, WinningNumber, Right(curNum, 2)) > 0 Then
    M = 2
    s = 2
    If InStr(1, WinningNumber, Left(curNum, 1)) > 0 Then M = M + 1
'any other scenario
Else
    s = 0
    For i = 1 To 3
        n = Mid(WinningNumber, i, 1)
        If InStr(1, curNum, n) > 0 Then
            M = M + 1
        End If
    Next
End If

Debug.Print "Matched digits: " & M
Debug.Print "Straight: " & s

我敢肯定有更好的方法来做,但这是我快速编写它的最简单方法。

相关问题