Forum Discussion
Averaging data every 2 cells using VBA
Try this:
Sub Average2()
Const fr = 2 ' First data row - change as needed
Dim ws As Worksheet
Dim wt As Worksheet
Application.ScreenUpdating = False
Set ws = ActiveSheet
Set wt = Worksheets.Add(After:=ws)
With wt.Range("A" & fr).Resize(43200, 24)
.Formula = "=AVERAGE(OFFSET('" & ws.Name & "'!A$" & fr & ",2*(ROW()-" & fr & "),0,2,1))"
.Value = .Value
End With
Application.ScreenUpdating = True
End Sub
- HansVogelaarNov 30, 2021MVP
Which column should be copied?
And do you want to copy the value from the even rows or from the odd rows in that column?
- Rory123908Nov 30, 2021Copper Contributor
Hi, to try and explain a bit better, the initial problem is describing output from a tool with various different variables, initially there was 86400 data points (1 per second of a day). These are in columns AL:BI (I have slightly adjusted your code so that it applies to these columns already). The new column I am talking about is in column "i". This represents the time at which the data points were recorded. It has already been sorted so that it is 43200 entries long. I am looking to export this time column alongside the variables which we have averaged in the initial problem. Additionally, I am trying to export them with their headers which currently lie on row 1. I hope this makes sense & thanks again for helping!
- HansVogelaarNov 30, 2021MVP
See if you can modify this for your purpose:
Sub Average2() Dim ws As Worksheet Dim wt As Worksheet Application.ScreenUpdating = False Set ws = ActiveSheet Set wt = Worksheets.Add(After:=ws) ' Copy headers in row 1 wt.Range("B1").Resize(1, 24).Value = ws.Range("AL1").Resize(1, 24).Value ' Copy column I to column A wt.Range("A1").Resize(43201).Value = ws.Range("I1").Resize(43201).Value ' Average data With wt.Range("B2").Resize(43200, 24) .Formula = "=AVERAGE(OFFSET('" & ws.Name & "'!AL$2,2*(ROW()-2),0,2,1))" .Value = .Value End With Application.ScreenUpdating = True End Sub