- I ask the user to put an input number like a "max" and then count and add all the even numbers together. For example: If the user inputs 6 then that would be 2+4+6 = 12
Sub AddupEvenNumbers()
Dim num As Variant
Dim evennum As Variant
Dim sum As Double
Dim str As String
Dim count As Integer
str = "Enter a upper/maximum number "
num = InputBox(str)
evennum = num
If num Mod 2 Then
evennum = num.Value + num
count = count + 1
End If
MsgBox "The sum of even numbers " & vbNewLine & "from 0 to " & num & vbNewLine & "is " & evennum
End Sub
>Solution :
you need to loop using a For loop and step 2:
Sub AddupEvenNumbers()
Dim num As Variant
Dim evennum As Long
Dim sum As Double
Dim str As String
Dim count As Integer
str = "Enter a upper/maximum number "
Do
num = InputBox(str)
If Not IsNumeric(num) Then str = "Must be a number." & vbNewLine & "Enter a upper/maximum number "
Loop While Not IsNumeric(num)
sum = 0
For evennum = 0 To num Step 2
sum = sum + evennum
Next evennum
MsgBox "The sum of even numbers " & vbNewLine & "from 0 to " & num & vbNewLine & "is " & sum
End Sub
Or use Application.InputBox(str,Type:= 1) to force a numeric entry
Sub AddupEvenNumbers()
Dim num As Double
Dim evennum As Long
Dim sum As Double
Dim str As String
Dim count As Integer
str = "Enter a upper/maximum number "
num = Application.InputBox(str, Type:=1)
sum = 0
For evennum = 0 To num Step 2
sum = sum + evennum
Next evennum
MsgBox "The sum of even numbers " & vbNewLine & "from 0 to " & num & vbNewLine & "is " & sum
End Sub