How to have my loop range be changing based on conditions

强颜欢笑 提交于 2020-02-08 03:51:52

问题


i don't know if my problem description is accurate, but basically i have this:

Since I'm working with positions here, each position comes in a pair. I want to loop through the whole list down and calculate the difference in value in each position pair (so i want to find the loss or the gain), and return it to another cell. here the difference between the 1st position pair is 14688, the following is another position. I've done a short code here to try to get the logic right, but it definitely isn't. any help here guys? Thanks a lot in advance. If im being vague with my question I will amend it.

The first position is in row 63.

Sub hello()

Dim sum As Long
Dim i As Long

For i = 63 To 100
    sum = range("T63").Value + range("T" & i)

    Do While sum <> 0
        If range("Y" & i) > 0 Then

'add result here

        End if
    Loop
Next

End Sub


回答1:


since your data "structure" has single not empty cells delimited by empty cells, then you could exploit the Areas property and the SpecialCells() method of Range object, like follows:

Option Explicit

Sub main()
    Dim iPair As Long
    Dim pairDiff As Double

    With Worksheets("lossgain") '<-- change "losspair" to your actual worksheet name
        With .Range("T63", .Cells(.Rows.Count, "T").End(xlUp)).SpecialCells(xlCellTypeConstants, xlNumbers) '<--| loop through column "T" cells containing numbers from row 63 down to last not empty one
            iPair = 1 '<--| initialize "pair" counter
            Do While iPair < .Areas.Count '<--| loop through "pairs"
                pairDiff = .Areas(iPair + 1).Offset(, 1) - .Areas(iPair).Offset(, 1) '<--| calculate the "pair" difference from corresponding column "U" values
                .Areas(iPair + 1).Offset(, IIf(pairDiff < 0, 2, 3)) = pairDiff '<--| write "pair" difference in corresponding column "V" (if loss) or "W" (if gain)
                iPair = iPair + 2 '<--| update "pair" counter by adding two not to mix "pairs"
            Loop
        End With
    End With
End Sub

follow comments and step through the code to see what's happening



来源:https://stackoverflow.com/questions/40281678/how-to-have-my-loop-range-be-changing-based-on-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!