当接受用户的3、4或5个数字时,返回平均值而不是总和

问题描述 投票:-2回答:1
Option Explicit
Sub btn_SumDigits()
    'Enter 2,3 or 4 numbers
    Dim SumTotal As Single, Numbers As Single, NumNumbers As Integer
    Dim One As Integer, Two As Integer, Three As Integer, Four As Integer
    Dim ValidInput As Boolean
    ValidInput = False
    Do While ValidInput = False
        'Converts what they enter to a number (value)
        'String data becomes 0
        Numbers = Val(InputBox("Enter a 2 to 4 digit number"))
        'Make sure enter a number between 2 and 4 length
        'Note converts the number to a string to find length (CStr)
        If Len(CStr(Numbers)) >= 2 And Len(CStr(Numbers)) <= 4 Then
            'Only way for the loop to stop!!
            ValidInput = True 'User entered legitimate value
            NumNumbers = Len(CStr(Numbers))
            One = Mid(Numbers, 1, 1)
            Two = Mid(Numbers, 2, 1)
            SumTotal = One + Two
            If NumNumbers > 2 Then 'Have 3 or 4 numbers
                Three = Mid(Numbers, 3, 1)
                SumTotal = SumTotal + Three
                If NumNumbers > 3 Then 'Have 4 numbers
                  Four = Mid(Numbers, 4, 1)
                  SumTotal = SumTotal + Four
                End If
            End If
         End If
    Loop
    MsgBox "The total of the digits " & Numbers & " is " & SumTotal
End Sub
excel vba
1个回答
0
投票

如前所述,循环从1到LEN(thenumber):

Sub btn_AvgDigits()
    Do
        Dim numbers As Long
        numbers = Application.InputBox("Enter a 2 to 4 digit number", Type:=1)
    Loop While Len(numbers) < 2 Or Len(numbers) > 4

    Dim sm As Long
    sm = 0

    Dim i As Long
    For i = 1 To Len(numbers)
        sm = sm + Val(Mid(numbers, i, 1))
    Next i

    MsgBox "The total of the digits " & numbers & " is " & sm & Chr(10) & _
            "The Average of the digits " & numbers & " is " & sm / Len(numbers)

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.