简体   繁体   English

VBA excel。 有条件循环

[英]VBA excel. Loop through with condition

I am looking to loop through Column A. 我希望遍历A列。
- If the next number is greater than the previous number continue (A: 0,1,2,3..). -如果下一个数字大于上一个数字,则继续(A:0,1,2,3 ..)。
- Do this until the next number is equal or less than (A: 0,1,2,3,4,4..). -这样做直到下一个数字等于或小于(A:0,1,2,3,4,4 ..)。
- If number is less than(A: 0,1,2,3,4,3..). -如果数字小于(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. 或等于,取最高的#4减去最低的#0,然后将结果放在columnB中最高编号旁边。
- If the next number is equal the previous number, subtract and put the answer 0 in columnB. -如果下一个数字等于上一个数字,则减去答案0并将其放在列B中。
- 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... -如果数字小于或等于,则取最高的#4减去最低的#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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