VBA – 使用InputBox的负数偶数

我很新的VBA,我希望如果有人能帮助我这个:

我必须编写一个要求用户使用input框input负偶数的下属。 子程序还需要将99和input的数字之间的所有偶数和,并将结果显示在消息框中。 它还必须包括validation初始input数字为负数的错误检查,如偶数和整数。

这是我想出来的,但它似乎并没有正常工作:

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 

请让我知道你们的想法。

确定下面的代码应该做的工作:

 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 
  • 如果NumberInput Mod 2为零,则NumberInput是偶数。 在这种情况下,你会显示一个错误信息,说这个数字不是偶数。 如果模数为零,则可能会触发该消息。

  • 当你检查input时,它还没有任何好处; 即使您显示错误消息,您也不会停止该程序。 所以即使出现错误,一旦用户点击消息框上的“确定”,子程序就会执行并产生结果。

    在发生错误的情况下,你需要返回,抛出一个exception,做一些事情来摆脱主代码path,并防止function的肉发生。