平均所有空白值error handling

我有一个循环的macros计算三个值的平均值。 在极less数情况下,所有这三个值都可能是空白的,所以我需要macros将这个平均值打印出来的单元格留空,然后继续下一个迭代循环。

我之前没有做过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 

这里是数据的截图

你可以调用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 

您可以尝试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