我的平均function是计数空白单元格为0

据我所知,Excel平均函数不包括空白的单元格。 不过,我的这个看起来正是我的代码所做的:

Sub sumavg() Dim rowCounter As Long Dim colCounter As Long Dim values() As Variant Const START_COL As Long = 1 Const END_COL As Long = 6 Const OUTPUT_COL_START As Long = 20 With Worksheets("datasummary") 'Load the values into an array values = .Range(.Cells(1, 1), .Cells(199, 18)).Value For rowCounter = 1 To 40 ReDim rowresults(1 To 1, START_COL To END_COL) For colCounter = START_COL To END_COL 'find average of AOIentries values rowresults(1, colCounter) = Application.WorksheetFunction.Average(values((5 * rowCounter - 2), colCounter), values((5 * rowCounter - 2), colCounter + 6), values((5 * rowCounter - 2), colCounter + 12)) Next colCounter 'print row of results .Range(.Cells(5 * rowCounter - 2, OUTPUT_COL_START), .Cells(5 * rowCounter - 2, OUTPUT_COL_START + END_COL - START_COL)).Value = rowresults For colCounter = START_COL To END_COL 'find average of RT values rowresults(1, colCounter) = Application.WorksheetFunction.Average(values((5 * rowCounter - 1), colCounter), values((5 * rowCounter - 1), colCounter + 6), values((5 * rowCounter - 1), colCounter + 12)) Next colCounter 'print row of results .Range(.Cells(5 * rowCounter - 1, OUTPUT_COL_START), .Cells(5 * rowCounter - 1, OUTPUT_COL_START + END_COL - START_COL)).Value = rowresults Next rowCounter End With End Sub 

这里是打印值包括空白单元格的代码:

 For r = 1 To UBound(d, 1) k = d(r, COL_BLOCK) & "|" & d(r, COL_TRIAL) 'create key If d(r, 19) = 1 Then dBT(k) = dBT(k) + IIf(d(r, COL_AOI) = "AOI Entry", 1, 0) 'get count Else: dBT(k) = "" End If Next r 'populate array with appropriate counts for each row For r = 1 To UBound(d, 1) k = d(r, 1) & "|" & d(r, 2) 'create key resBT(r, 1) = dBT(k) 'get the count Next r Call createsummarytable Call PopSummaryAOI(dBT) dBT.RemoveAll For r = 1 To UBound(d, 1) k = d(r, COL_BLOCK) & "|" & d(r, COL_TRIAL) 'create key dBT(k) = d(r, COL_RT) Next r 

以下是平均函数的数据截图

据我所知,细胞是完全空白的,所以它不应该被包括在平均值中,但是(20 + 17)/ 2 = / = 12.33,而(20 + 17 + 0)/ 3 = 12.33。

当你调用.Range(.Cells(1, 1), .Cells(199, 18)).Value ,你最终会得到一个Variant数组。 WorksheetFunction.AverageRangeVariant数组视为与对待Variant不同。 如果你给它个别的Variant参数,它把它们转换成Double s,而将Empty转换成Double结果为0.如果你想让它忽略空单元格,你需要传递RangeVariant()

 Sub Example() Dim test As Variant test = Empty 'This is what you get from an EmptyCell.Value Debug.Print CDbl(test) 'Prints 0. Debug.Print WorksheetFunction.Average(test, 0, 10) 'Prints 3.33333333333333. Range("A1").ClearContents 'Nothing in A1 now. Debug.Print Range("A1").Value = Empty 'Prints True Debug.Print WorksheetFunction.Average(Range("A1"), 0, 10) 'Prints 5 End Sub