![Excelで最初の入力番号から2番目の入力番号までの番号シーケンスを作成する](https://rvso.com/image/1518659/Excel%E3%81%A7%E6%9C%80%E5%88%9D%E3%81%AE%E5%85%A5%E5%8A%9B%E7%95%AA%E5%8F%B7%E3%81%8B%E3%82%892%E7%95%AA%E7%9B%AE%E3%81%AE%E5%85%A5%E5%8A%9B%E7%95%AA%E5%8F%B7%E3%81%BE%E3%81%A7%E3%81%AE%E7%95%AA%E5%8F%B7%E3%82%B7%E3%83%BC%E3%82%B1%E3%83%B3%E3%82%B9%E3%82%92%E4%BD%9C%E6%88%90%E3%81%99%E3%82%8B.png)
選択した 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 でトリガーできます。偶数をチェックしていることに注意してください (また、ゼロを正の数 (または負の数) とは見なさないことに注意してください)。
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