不一致的条件评估
有时,While
循环会在条件评估False
时执行一次额外的时间。
例如,如果我输入1作为开始,3表示结束,0.05作为步骤。
Private Sub CommandButton21_Click()
Dim StrPrompt As String
Dim StepValue As Double
Dim StartValue As Double
Dim EndValue As Double
Dim CurrentValue As Double
StrPrompt = "Enter a Positive start number."
redo:
StartValue = Application.InputBox(StrPrompt, "Start", , , , , , Type:=1)
If Not (StartValue >= 0) Then
StrPrompt = "Please enter a postive number."
GoTo redo
End If
MsgBox "User entered " & StartValue, , "Start Value"
Cells(1, 4) = StartValue & " Start"
StrPrompt = "Enter a Positive end number."
redo1:
EndValue = Application.InputBox(StrPrompt, "End", , , , , , Type:=1)
If EndValue <= StartValue Then
StrPrompt = "Please enter a number larger than start number."
GoTo redo1
End If
MsgBox "User entered " & EndValue, , "End Value"
Cells(1, 4) = EndValue & " End"
StrPrompt = "Enter a Positive step value."
redo2:
StepValue = Application.InputBox(StrPrompt, "Step", , , , , , Type:=1)
If Not (StepValue > 0) Then
StrPrompt = "Please enter a number > 0."
GoTo redo2
End If
MsgBox "User entered " & StepValue, , "Step Value"
Cells(1, 4) = StartValue & " Step"
CurrentValue = StartValue
Cells(1, 4) = CurrentValue
While CurrentValue < EndValue
' MsgBox "Current Value before increment " & CurrentValue, , "Before"
CurrentValue = CurrentValue + StepValue
'MsgBox "Current Value after increment " & CurrentValue, , "After"
Cells(1, 4) = CurrentValue
Wend
End Sub