I have a spreadsheet where I'm trying to repeatedly populate column K with specific data from various but similar points (80 cells down for each iteration) in column E.
So K2 should for example display the total of E25 + E35 + E42 + E56 + E63.
Then K3 should display the total of E105 + E185 + E122 + E136 + E143.
I have written a macro which does the first step (and works), which is as follows:
Sub disctoptest()
Dim source As Range
Dim destination As Range
Dim total As Long
Set destination = Range("K2")
Set source = Range("E25")
total = WorksheetFunction.Sum( _
source.Value + _
source.Offset(10, 0).Value + _
source.Offset(17, 0).Value + _
source.Offset(31, 0).Value + _
source.Offset(38, 0).Value)
destination.Select
destination.Value = total
Set source = Nothing
Set destination = Nothing
End Sub
Then I inserted a loop to repeat the operation for the entirety of the database, but whenever I run the added macro excel either freezes or simply refuses to work. This is the code I'm using to loop:
Sub disctop()
Dim source As Range
Dim destination As Range
Dim total As Long
Set destination = Range("K2")
Set source = Range("E25")
Do until destination.offset(0, -1) = ""
destination.Select
total = WorksheetFunction.Sum( _
source.Value + _
source.Offset(10, 0).Value + _
source.Offset(17, 0).Value + _
source.Offset(31, 0).Value + _
source.Offset(38, 0).Value)
destination.Value = total
source = source.Offset(80, 0)
destination = destination.Offset(1, 0)
Loop
Range("A1").Activate
Set source = Nothing
Set destination = Nothing
End Sub
In case it might be easier to use a different kind of loop, I need to repeat the operation precisely 680 times in column K.
Any tips and advice would be greatly appreciated!
You need to use SET
on the range variables to make them change to which cell they reference:
Set source = source.Offset(80, 0)
Set destination = destination.Offset(1, 0)
Also
destination.offset(0, -1) = ""
will never return true as the SUM function will return 0 even when all five references are empty.
So you will need to test something else like: Total = 0
Or you can do this with the following formula:
=INDEX(E:E,25+((ROW(1:1)-1)*80)) +INDEX(E:E,35+((ROW(1:1)-1)*80)) +INDEX(E:E,42+((ROW(1:1)-1)*80)) + INDEX(E:E,56+((ROW(1:1)-1)*80)) +INDEX(E:E,63+((ROW(1:1)-1)*80))
Put in K2 and copy down.
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.