. This problem will give you practice using a Do/While loop in VBA. Write a VBA
ID: 3628350 • Letter: #
Question
. This problem will give you practice using a Do/While loop in VBA. Write a VBA function called “sequence” that allows the user to specify a limit (a positive number). For this limit, your function should return the smallest number n where the sum 1 + 2 + … + n is greater than the specified limit. Your function should have the following general form:
1. Begin by assuming that n is 0
2. Also, assume that the sum is initially 0
3. Set up a Do/While loop that iterates while the sum does not exceed the specified limit
4. Inside the loop, increase n by 1 (e.g., n = n + 1)
5. Also inside the loop, update the sum to include the new n value
You can verify that your function is working by trying these cases. If the limit is 6, then n = 4. If the limit is 40, then n = 9.
Explanation / Answer
Function sequence(lim As Double) As Integer 'lim - the user entered limit Dim n As Integer 'smallest number for sum of 1+2+...+n > lim Dim sum As Integer 'Sum of integers must also be an integer 'Initialize n = 0 sum = 0 'Check input (optional) If Not (lim > 0) Then 'warn user to enter a positive number MsgBox "Entry must be greater than 0" 'exit the function sequence = 0 Exit Function End If 'Loop 'Note, user must enter positive number, since sum starts 'at 0, loop must itterate at least once to get sum>lim 'therefore check loop condition at end of loop Do 'increment n n = n + 1 'add n to sum sum = sum + n Loop While sum <= lim 'check to see if we made it '(sum must be > limit so we must continue if we are <= lim) 'if we made it, loop will exit, n will be the number we need 'Return n sequence = n End FunctionRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.