내가 선택한 2개의 숫자 중 메시지 상자에 숫자를 쓰고 싶습니다. 짝수인지 확인하는 동안 가장 작은 숫자부터 가장 큰 숫자여야 합니다. 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
나는 조금 다르게 할 것입니다. command_button을 사용하여 이를 트리거할 수 있습니다. 나는 짝수를 확인합니다. 또한 0을 양수(또는 음수)로 간주하지 않습니다.
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