我的平均功能是将空白单元格计为0

时间:2016-12-01 04:33:16

标签: excel vba function

据我所知,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

Here is a screenshot of the data the average function works on

据我所知,单元格完全是空白的,所以不应该包含在平均值中,但是(20 + 17)/ 2 = / = 12.33,而(20 + 17 + 0)/ 3 = 12.33。

1 个答案:

答案 0 :(得分:2)

当您致电.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