Hello. Any help with this would be very much appreciated. Currently I have a routine that averages an interval of data within column B based on a unique value in column A. It places the newly processed range within columns C:D. Works great, but now I need it to work over a series of columns.
For example, currently if A1:A10=the same unique value, routine sums and averages B1:B10, unique value is displayed within C1, and average value from B1:B10 are in D1.
In my new case, the data will not be constrained to just column B and can have varying column count. I've tried to revise the code to account for a varying column count, but am having problems with the code. Can anyone see where my logic or syntax can be accounted for? I also think it would be easier to put the averaged data on a separate sheet within the second For statement.
For example, currently if A1:A10=the same unique value, routine sums and averages B1:B10, unique value is displayed within C1, and average value from B1:B10 are in D1.
In my new case, the data will not be constrained to just column B and can have varying column count. I've tried to revise the code to account for a varying column count, but am having problems with the code. Can anyone see where my logic or syntax can be accounted for? I also think it would be easier to put the averaged data on a separate sheet within the second For statement.
Code:
Public Sub Final_output()
Dim inputLR As Long, outputLR As Long
Dim cel As Range, aRng As Range, bRng As Range
Dim dict As Object, c As Variant, i As Long
Set dict = CreateObject("Scripting.Dictionary")
Set ws = ThisWorkbook.Worksheets("test") 'your data sheet
With ws
lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
inputLR = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row in column A unique value - independent variable
Set aRng = .Range(.Cells(2, 1), .Cells(inputLR, 1)) 'data range in column A unique value - independent variable
Set bRng = .Range(.Cells(2, 2), .Cells(inputLR, lCol)) 'data range in column values to be averaged - dependent variable
c = aRng
For i = 1 To UBound(c, 1)
dict(c(i, 1)) = 1
Next i
.Cells(lCol).Resize(dict.Count) = Application.Transpose(dict.keys) 'display uniques from column A in last column
outputLR = .Cells(.Rows.Count, .Cells(.Rows, lCol)).End(xlUp).Row 'last row in last column of data of stored unique value processed from column A.................Type mismatch error here
For Each cel In .Range(.Cells(2, lCol), .Cells(outputLR, lCol)) 'loop through each cell where the unique value is stored
cel.Offset(0, 1) = Application.WorksheetFunction.AverageIf(aRng, cel, bRng) 'calculate average
Next cel
End With
End Sub
Last edited: