Solved

# Algorithm for "For Loop" on vba

Posted on 2011-10-27
Medium Priority
287 Views
I want to add numbers in arrays (20 each), in a trailing fashion. So, I think it is going to look like the following.

Y1=X1
Y2=X2
Y1=X1+X2 (OR Y1+X2)
Y3=X3
Y1=X1+X2+X3 (OR Y1+X3 OFCOURSE)
Y2=X2+X3 (OR Y2+X3)

So each Y will be addition of the 20 numbers. so Y(1) will be the addition of the numbers between X1-X20.

How can I construct the for loop for this?

thanks
0
Question by:awesomejohn19
• 3
• 2

LVL 37

Expert Comment

ID: 37041175
Y(1) = X(1)
For i = 2 To 20
Y(i) = X(i) + Y(i-1)
Next
0

Author Comment

ID: 37041437
thanks for your response. I think I did not ask my question correctly.

Each Y will be addition of 20 numbers
but there are a total of 5000 numbers.
Y1 will be the addition of X1-X20
Y2 will be the addition of X2-X21
..
Ylast will be the addition of X4980-X5000
0

LVL 27

Expert Comment

ID: 37041674
I believe the following nested loops will work:
``````For i = 1 To 4980
For j = 1 To 20
y(i) = y(i) + x(j + i - 1)
Next j
Next i
``````
0

LVL 37

Accepted Solution

TommySzalapski earned 2000 total points
ID: 37042053
Or to be more efficient
``````Y(1)=0
For i=1 To 20
Y(1)=Y(1)+X(i)
Next
For i=21 To 5000
Y(i-19)=Y(i-20)+X(i)-X(i-20)
Next
``````
0

Author Comment

ID: 37046346
Tommy, I think yours is correct if we add 19 to 5000.

Y(1)=0
For i=1 To 20
Y(1)=Y(1)+X(i)
Next
For i=21 To 5000 + 19
Y(i-19)=Y(i-20)+X(i)-X(i-20)
Next
0

LVL 37

Expert Comment

ID: 37046575
No. That is wrong because when i = 5001, X(i) does not exist.
If the size of Y is 4980, then my code is correct. If the size of Y is 5000, then what is to be done with Y(4981) and above?
Should Y(4991) be the Xs from 4991 to 5000 or from 4991 to 5000 and from 1 to 10 to make the full 20?
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you need to forecast numbers -- typically for finance -- the Windows and Mac versions of Excel 2016 have a basket of tools to get the job done.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
Starting up a Project
###### Suggested Courses
Course of the Month13 days, 16 hours left to enroll