0

Im very new on VBA and i was hoping if anyone could help me out on this:

I have to write a subordinate that requests the user to enter a negative even integer using an input box. The subroutine also needs to sum all the even integers between 99 and the inputted number and display the result in a message box. It must also must include error checking that validates the initial inputted number as negative, as even, and as an integer.

This is what i came up with but it doesn't seem to be working proper:

Option Explicit

Sub NegativeEvenIneteger()

    Dim Sum As Double
    Dim NumberInput As Integer
    Dim x As Double

    NumberInput = InputBox("Please Enter a Negative Even Integer")

    If NumberInput >= 0 Then MsgBox ("ERROR, Input number must be Negative")
    If NumberInput Mod 2 = 0 Then MsgBox ("ERROR, Input number must be Even")

    Sum = 0
    For x = NumberInput + 1 To 0 Step 2
        Sum = Sum + x
    Next

    MsgBox ("This equals " & Sum) & vbCrLf & _
    ("based on the inputted number of ") & NumberInput

End Sub

Please let me know what you guys think.

4

2 回答 2

1

OK the following code should do the job:

Option Explicit

Sub NegativeEvenIneteger()

Dim Sum As Double
Dim NumberInput As Integer
Dim x As Double
Dim NumberError As Boolean: NumberError = True
NumberInput = InputBox("Please Enter a Negative Even Integer")

If IsNumeric(NumberInput) Then 'test for number
    If Not NumberInput Like "*.*" Then 'test for decimal
        If NumberInput < 0 Then 'test for negative
            If NumberInput Mod 2 = 0 Then
                Sum = 0
                For x = NumberInput To 98 Step 2
                    Sum = Sum + x
                Next
                NumberError = False
            End If
        End If
    End If
End If

If NumberError Then
    MsgBox "not a valid input"
Else
    MsgBox ("This equals " & Sum) & vbCrLf & ("based on the inputted number of ") & NumberInput
End If

End Sub
于 2013-10-09T17:03:23.200 回答
1
  • If NumberInput Mod 2 is zero, then NumberInput is even. You show an error message in that case saying that the number isn't even. That message should probably be triggered if the modulus isn't zero.

  • While you're checking the input, it doesn't do any good yet; even though you show an error message, you don't stop the program. So even if there's an error, once the user clicks "OK" on the message box, the subroutine soldiers on and produces results it shouldn't.

    In the case of an error, you need to return, throw an exception, do something to get off the main code path and prevent the meat of the function from happening.

于 2013-10-09T17:03:36.690 回答