所有空白值的平均值错误处理

时间:2016-12-12 03:04:21

标签: excel vba error-handling

我有一个循环宏来计算三个值的平均值。在极少数情况下,所有三个值都可能为空,因此我需要宏,然后将平均值打印的单元格留空,并继续循环的下一次迭代。

之前我还没有完成错误处理,所以不确定最好的方法。这是我的代码:

Sub sumavg()
        Dim i As Long, j As Long
        With Worksheets("datasummary")
            For i = 1 To .Range("A" & .Rows.Count).End(xlUp).Row Step 5
                For j = 1 To 6
                    With .Rows(i + 2)
                        .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10))
                    End With
                    With .Rows(i + 3)
                        .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10))
                    End With
                Next
            Next

        End With
    End Sub

Here is a screenshot of the data

2 个答案:

答案 0 :(得分:1)

您可以尝试On Error Resume Next或只是将零添加到您要平均的值。

Sub sumavg()
    Dim i As Long, j As Long
    With Worksheets("Sheet2")
        For i = 1 To .Range("A" & .Rows.Count).End(xlUp).Row Step 5
            For j = 1 To 6
                With .Rows(i + 2)
                    .Columns(19 + j).Value = WorksheetFunction.Average(.Columns(j) + 0, .Columns(j + 5) + 0, .Columns(j + 10) + 0)
                End With
                With .Rows(i + 3)
                    .Columns(19 + j).Value = WorksheetFunction.Average(.Columns(j) + 0, .Columns(j + 5) + 0, .Columns(j + 10) + 0)
                End With
            Next
        Next

    End With
End Sub

答案 1 :(得分:1)

您可以调用Application对象的Average()函数,并检查其结果是否出错:

Sub sumavg()
    Dim i As Long, j As Long
    Dim res As Variant '<--| this will store the result of Application.Average() function

    With Worksheets("datasummary")
        For i = 1 To .Range("A" & .Rows.count).End(xlUp).row Step 5
            For j = 1 To 6
                With .Rows(i + 2)
                    res = Application.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10))
                    If Not IsError(res) Then .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10))
                End With
                With .Rows(i + 3)
                    res = Application.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10))
                    If Not IsError(res) Then .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10))
                End With
            Next
        Next

    End With
End Sub