Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA Code: How would you count even numbers and add them together

  • 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading