问题
I'm new in this stuff of programming. I'have been searching for this topic and I can't find anything that fits to my problem.
I have an array of data with measures. I have 31 lines and 96 columns. I want that my VBA code finds the average of each column of data and displays it on the line after the last value of the column.
Can anybody help me?
Thanks in advanced.
回答1:
The easiest answer I've found is to use the following:
Application.WorksheetFunction.Average(dataArray)
This is (hypothetically) the same as using the average function in a worksheet. The only downside seems to be that you have to use an array or some other list of data points. This is easily remedied with the following:
Function getArray(dataRange As Range) As Variant()
Dim arr(dataRange.Rows.Count, dataRange.Columns.Count) as Variant
Dim i as Integer, j as Integer
For i = 1 to dataRange.Rows.Count
For j = 1 to dataRange.Columns.Count
arr(i, j) = dataRange(i, j)
Next
Next
getArray = arr
End Function
This will convert the range into an array and will be accessible through the Average
function. For instance:
myAverage = Application.WorksheetFunction.Average(getArray(Range("C1:CT56")))
回答2:
You can enter a formula in the line below the data:
=average(A1:A96)
Isn't that easier than using VBA for this purpose?
If you really want to use VBA:
Sub ownaverage()
Dim totalsum As Double
Dim totalnum As Double
Dim ownav As Double
totalsum = 0
totalnum = 0
For Each c In Worksheets("Sheet1").Range("D17:E17").Cells
totalsum = totalsum + c.Value
totalnum = totalnum + 1
Next
ownav = totalsum / totalnum
ownaverage = ownav
Range("I27").Select
ActiveCell.FormulaR1C1 = ownaverage()
End Sub
Reference for loops: http://msdn.microsoft.com/en-us/library/office/aa221353(v=office.11).aspx
回答3:
Thanks again for the answer. I was able to figure it out by myself. The code I wrote is:
Private Sub CommandButton2_Click()
Dim soma as Double
Dim media as Double
soma=0
media=0
totalnum=0
With Sheets("sheet1")
For j= 1 to 96
For i =28 to 58
Set target = Cells (i,j)
soma=soma+targe
totalnum=totalnum+1
Next i
Cells(i+1,j).Value = soma/totalnum
soma=0
totalnum=0
Next j
End With
End sub
I hope this code help someone with the same doubts as I had.
Thanks again DaveG
来源:https://stackoverflow.com/questions/26926902/average-of-an-array-of-data-vba-excel