简体   繁体   中英

VBA excel. Loop through with condition

I am looking to loop through Column A.
- If the next number is greater than the previous number continue (A: 0,1,2,3..).
- Do this until the next number is equal or less than (A: 0,1,2,3,4,4..).
- If number is less than(A: 0,1,2,3,4,3..). or equal, take the highest # 4 subtract lowest #0, and put the results in columnB next to the highest number.
- If the next number is equal the previous number, subtract and put the answer 0 in columnB.
- If the next number is lower than the previous number continue. Do this until the next number is equal or less than.
- If number is less than or equal, take the highest # 4 subtract lowest #0...

I am not sure If I am clear but I am thinking a loop might work for this situation. Or perhaps any other idea would be greatly appreciated. Thanks in advance.

     A   B
1    0   
2    1
3    2
4    3
5    4   4
6    4   0
7    3
8    2
9    1
10   0   4
11   1
12   2   2
13   2   0
14   3
15   4   2
...  ...  

You can use dictionary... adding the row number to the key value and check the positions...

 Sub YourLoop()

   Dim dic As Scripting.Dictionary
   Set dic = New Scripting.Dictionary

   Dim i As Integer
   Dim n As Integer

For i = 1 To Rows.Count

     ''ColumnA values
     dic.Add i, Cells(i, 1).Value

Next i


Dim k1 As Integer
Dim k2 As Integer
Dim k3 As Integer
Dim k4 As Integer

Dim v1 As Integer
Dim v2 As Integer
Dim v3 As Integer
Dim v4 As Integer
Dim v As Integer

Dim c As Integer
c = 1

For Each key In dic.Keys

   v = dic(key)

   If c = 1 Then
    ''do nothing
   ElseIf c = 2 Then
    k1 = key - 1
    v1 = dic(k1)

    If v <= v1 Then

    End If

   ElseIf c = 3 Then
    k2 = key - 2
    k1 = key - 1

    v1 = dic(k1)
    v2 = dic(k2)


   ElseIf c >= 4 And c < dic.Count Then

    k4 = key - 4
    k3 = key - 3
    k2 = key - 2
    k1 = key - 1

    v1 = dic(k1)
    v2 = dic(k2)
    v3 = dic(k3)
    v4 = dic(k4)

    ElseIf c = dic.Count Then

    End If

    c = c + 1
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM