1. Write a Sub that requests a positive integer with an InputBox. Then it uses a
ID: 672959 • Letter: 1
Question
1. Write a Sub that requests a positive integer with an InputBox. Then it uses a For loop to sum all of the odd integers up to the input number, and it displays the result in a MsgBox.
2. like question1, make it enters all of the odd integers in consecutive cells in column A, starting with cell A1, and it shows the sum in the cell just below the last odd integer.
i already down the question 1, but i don't know how to put odd intergers and sum in consecutive cells in colmn A?
thanks for the help.
this is my code for question1
Sub ForLoop()
Dim i As Integer
Dim sum As Long
Dim maxN As Integer
maxN = InputBox("Enter a positive integer:")
For i = 1 To maxN
sum = sum + i
i = i + 1
Next i
MsgBox "The sum of the first " & maxN & " integers is " & sum
End Sub
Explanation / Answer
Program for Sub that requests a positive integer with an InputBox. Then it uses a For loop to sum all of the odd integers up to the input number, and it displays the result in a MsgBox.
Sub ForLoop()
Dim i As Integer
Dim sum As Long
Dim maxN As Integer
maxN = Val(InputBox("Enter a positive integer:", "Input"))
If maxN = "" Or maxN < 1 Then
MsgBox "Invalid entry. Must be a positive number", vbCritical, "Value entered: " & maxN
Exit Sub
End If
For i = 1 To maxN
If i Mod 2 <> 0 Then
sum = sum + i
End If
Next
MsgBox "The sum of the firstand " & maxN & "integers is" & sum
End Sub
like question1, make it enters all of the odd integers in consecutive cells in column A, starting with cell A1, and it shows the sum in the cell just below the last odd integer.
Sub ForLoopTwo()
Dim i,j As Integer
Dim sum As Long
Dim maxN As Integer
j = 1
Columns("A:A").ClearContents
Columns("A:A").Interior.ColorIndex = xlNone
maxN = Val(InputBox("Please enter a positive integer (whole number)", "Input"))
If maxN = "" Or maxN < 1 Then
MsgBox "Invalid entry. Must be a positive number", vbCritical, "Value entered: " & maxN
Exit Sub
End If
For i = 1 To maxN
If i Mod 2 <> 0 Then
sum = sum + i
Cells(j, "A").Value = i
j = j + 1
End If
Next
Range("A" & Rows.Count).End(xlUp).Offset(1).Value = sum
Range("A" & Rows.Count).End(xlUp). Interior.ColorIndex = 15
End Sub
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.