我想在訊息框中寫出我選擇的兩個數字之間的數字。在檢查它們是否是偶數時,它們必須是從最小到最大的數。這 2 個數字必須為正且小於 100。
我在 Excel 中使用 Visual Basic,但我以前從未使用過它。
Private Sub CommandButton1_Click()
Dim a, b, P, i As Integer
a = InputBox("Write number from 1 to 100 ")
If a <= 0 Or a >= 100 Then
MsgBox "Wrong input"
Exit Sub
End If
b = InputBox("Write number from 1 to 100 ")
If b <= 0 Or b >= 100 Then
MsgBox "Wrong input"
Exit Sub
End If
For i = a To b
If a <> 0 & a <= b Then
a = a + 1
Else
P = a
a = a + 1
Exit For
End If
Next i
MsgBox P
End Sub
答案1
我會做得有點不一樣。您當然可以使用命令按鈕觸發此操作。請注意,我檢查偶數(而且我也不認為零是正數(或負數)。
Option Explicit
Sub CreateSequence()
'Note each variable must have a type declaration,
' else they will be of type Variant
Dim x As Long, y As Long, z As Long
Dim S As String
x = InputBox("First Number")
y = InputBox("Second Number")
If Not CheckNum(x) Or Not CheckNum(y) Then
MsgBox "Both numbers must be positive and less than 100"
Exit Sub
End If
If x > y Then 'reverse x and y
z = y
y = x
x = z
End If
For z = x To y
'check if even and add to string if they are
If z Mod 2 = 0 Then S = S & vbLf & z
Next z
'Remove the leading separator (vbLf)
S = Mid(S, 2)
MsgBox S
End Sub
Function CheckNum(L As Long) As Boolean
If L > 0 And L < 100 Then
CheckNum = True
Else
CheckNum = False
End If
End Function