I have written the code below in which I have to first identify smallest, 2nd smallest and so on numbers and then obtain the row numbers for them (I am saving the row numbers in a separate column, here column 50, in case there are more than one such number) and copy contents from one column (Here column 2) to another (Here Column 7) in the order of the row numbers, i.e. Smallest first, then 2nd smallest, and so on.
There are 172 such data sets starting at every 43 rows
This will continue till the sum of the numbers in the new column (45 row of Column 7 of each dataset) (To which the data is copied) is less than a specified number (45 row of Column 1 in every data set, i.e., A45 then A88)
EDIT: The sums being compared above, i.e. G45 is compared to A45 is through formula in the sheet itself
Dim m As Range, cl As Range, k As Double, b As Double, lIndex As Double, a As Double, multi As Double, l As Integer, x As Double
Set m = ActiveSheet.Range("E3:E40")
multi = 2 'To move to starting position of the data set
For i = 1 To 172
b = 45 + 43 * (i - 1)
For k = 1 To 38
a = Application.Small(m, k) 'To find the kth smallest number
l = 1
For j = 1 To 38 'To store the matching row numbers (Multiple instances) in column 50
Cells(j, 50).Value = 0 'Initializing to column no. 50 to 0
If Cells(j + multi, 5).Value = a Then 'Checking for match
Cells(l, 50).Value = j + multi 'Storing Row coordinates in column no. 50
l = l + 1
End If
Next j
'==============THE FOLLOWING IS THE AREA WHERE THE PROBLEM MIGHT BE======================
For o = 1 To l - 1 'To Copy the values based on the criteria
x = Cells(o, 50).Value
If Cells(b, 7).Value <= Cells(b, 1).Value Then '"CRITERIA" Checking whether sum of the column is less than or equal to sum of first column of set
Cells(x, 7).Value = Cells(x, 2).Value
End If
Next o
Next k
Set m = m.Offset(43)
multi = multi + 43
Next i
The problem is that the condition for copying copy (The sum should be less than certain value) is not working. It actually copies all the data from column 2 to column 7.
Can someone help in finding what might be the reason for this...
NOTE: I checked and confirmed that the code to store row numbers in column 50 is working fine. So the problem might be in the lower half of the code which is the for loop with variable "o"