Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

More efficient way to average array element?

Status
Not open for further replies.

osx99

Technical User
Apr 9, 2003
250
GB
I have a 2 dimensional array - write_array(1 to 23, 1 to 7)

When populated slice write_array(2,x) typically look something like this with variation of times and Empty entries

write_array(2,1) = "TIME"
write_array(2,2) = 23.08
write_array(2,3) = 22.58
write_array(2,4) = 23.02
write_array(2,5) = Empty
write_array(2,6) = Empty
write_array(2,7) = 24.02

Where the array element is Empty I want to replace with the average time of the others so Empty would be replaced with (23.08+22.58+23.02+24.02)/4

I have the following code which does this
Code:
'average recent time
        recenttimecount = 0
        rtSum = 0
        recenttime = Application.WorksheetFunction.index(write_array, 2, 0)
        For rtcount = 2 To UBound(recenttime)
        If Not IsEmpty(recenttime(rtcount)) Then
        recenttimecount = recenttimecount + 1
        rtSum = rtSum + recenttime(rtcount)
        End If
        Next
        recenttimeAvg = rtSum / recenttimecount
        For rtcount = 2 To UBound(recenttime)
        If IsEmpty(recenttime(rtcount)) Then
        write_array(2, rtcount) = recenttimeAvg
        End If
        Next

Is there a more efficient way of doing this without 2 FOR loops?

Thanks,
Os
 
I found an alernative solution to this

Code:
        recenttimeAvg = Round(Application.WorksheetFunction.Average(Application.WorksheetFunction.index(write_array, 2, 0)), 2)
        For rtcount = 1 To UBound(write_array, 2)
        If IsEmpty(write_array(2, rtcount)) Then write_array(2, rtcount) = recenttimeAvg
        Next rtcount
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top