问题
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