WorksheetFunction.AverageIf的运行时错误“1004”

我目前的问题涉及使用AverageIf函数来计算某些事件的平均时间(flavor改变,大小更改和标签更改)。 我写了三段不同的代码来计算每个事件的平均时间。 所有三个部分是相同的(相同的标准范围,和平均范围)唯一的区别是标准。

但是,当我运行macros时出现以下错误:

运行时错误“1004”无法获取WorkksheetFunction类的AvergeIf属性

此错误只发生在代码的标签更改部分。

我的一些疑难解答:

  • validation单元格中的string长度是否与代码中的string相同
  • 确认时间是数字格式
  • 检查范围

这是我的代码片段:

 'Set Criteria Range for Averages Set crng = Range(Worksheets("DataImport").Cells(StartRowT, "E"), Worksheets("DataImport").Cells(LastRowT, "E")) 'Set Average time ranfe for Averages Set trng = Range(Worksheets("DataImport").Cells(StartRowT, "G"), Worksheets("DataImport").Cells(LastRowT, "G")) 'Flavor Change If I > 0 Then FlavorA = Application.WorksheetFunction.AverageIf(crng, "Flavor Change", trng) Else FlavorA = 0 End If 'Size Change If M > 0 Then SizeChangeA = Application.WorksheetFunction.AverageIf(crng, "Size Change", trng) Else SizeChangeA = 0 End If 'Label Change If J > 0 Then LabelA = Application.WorksheetFunction.AverageIf(crng, "Label Change", trng) Else LabelA = 0 End If 
  • 字母variables是事件总数的计数variables
  • crng是标准范围
  • trng是时间范围(平均范围)

我仍然试图找出代码的标签更改部分的运行时错误1004的确切原因。

如果条件不匹配(并且您获得#DIV / 0),那么这会在您的VBA中触发运行时错误。 相反,您可以使用Application.AverageIf()版本(即删除WorksheetFunction )不会抛出运行时错误,然后使用IsError()testing返回值

 Dim m 'Label Change If J > 0 Then m = Application.AverageIf(crng, "Label Change", trng) LabelA = IIf(IsError(m),"value when no match", m) Else LabelA = 0 End If 

这个错误是由于你的crng范围内没有任何“Label Change”值而引起的,所以你实际上试图用0除以crng #DIV/0

您可以在计算范围的平均值之前添加一个testing标准,使用下面的代码(每个平均值计算)

 ' at least once cell in the range has the value of "Label Change" If WorksheetFunction.CountIf(crng, "Label Change") > 0 Then LabelA = Application.WorksheetFunction.AverageIf(crng, "Label Change", trng) Else ' pop a message-box, or whatever you want MsgBox "'Label Change' value is not found in range " & crng.Address End If