我正在Error '424': Object Required
当我尝试运行以下子程序时:
Sub MySub()
'Iterate through column, setting corresponding values
For Each cell In Range("Table5[Name]")
cell.Offset(, 2).Value = Avg("Table2[time]", cell.Value, "Table2[name]")
cell.Offset(, 3).Value = StDev("Table2[time]", cell.Value, "Table2[name]", cell.Offset(, 2).Value)
Next
End Sub
当我按下调试时,它突出显示For循环内的第二行。 Avg
和StDev
都是我写的与AVERAGEIF
类似的函数,但是在非常具体的情况下。
Avg
功能完全符合预期,StDev
几乎相同。它有一个额外的If
语句,数学几乎相同。这两个函数都返回Variant
。
我无法弄清楚它为什么会这样做。到目前为止,我已经尝试在麻烦的线前添加Set
(我知道它不会起作用,但我还是要尝试),而且我已经确定这两个功能都是安全(即它们不会除以零,它们总是返回一个值)。
这里是StDev功能(为了保护工作机密而修改,但有同样的问题):
Function StDev(rng As Range, Criteria1 As Variant, Criteria_Rng1 As String, Optional avg As Variant) As Variant
'Call like this
' StDev2Ifs(Range to StDev, Match this, Range to find Criteria1, [average])
If IsMissing(avg) Then
avg = Avg(rng, Critera1, Criteria_Rng1)
End If
If avg <> "NO DATA" Then
'Convert Strings to Ranges
Dim c_rng, c_rng1 As Range
Set c_rng = Application.Range(rng)
Set c_rng1 = Application.Range(Criteria_Rng1)
'Get Column Indices
Dim r, r1As Long
r = c_rng.Columns(c_rng.Columns.Count).Column
r1 = c_rng1.Columns(c_rng1.Columns.Count).Column
'Calculate column offsets from range to stdev
Dim off1 As Long
off1 = r1 - r
'x will be used to sum the elements
Dim x As Double
x = 0
'ct will be used to count number of elements
Dim ct As Double
ct = 0
For Each cell In Range(rng)
If cell.Offset(, off1).Value = Criteria1 Then
x = x + Square(cell.Value - avg)
ct = ct + 1
End If
Next
'Divide by count
If ct <> 0 Then
StDev = x / ct
Else
StDev = "NO DATA"
End If
'Square Root
If ct <> 0 Then
StDev = StDev ^ (1 / 2)
End If
Else
StDev = "NO DATA"
End If
End Function
有人有什么想法吗?
答案 0 :(得分:0)
cell.Offset(, 3).Value = StDev("Table2[time]", cell.Value, "Table2[name]", cell.Offset(, 2).Value)
第一个代码块中的应该是
cell.Offset(, 3).Value = StDev(Range("Table2[time]"), cell.Value, "Table2[name]", cell.Offset(, 2).Value)
如果您打算按功能预期传递范围。您将遇到一个严重的错误,因为在您的函数中,StDev似乎是为了将其作为字符串传递而构建的,因此我建议您更正函数
Function StDev(rng As Range, Criteria1 As Variant, Criteria_Rng1 As String, Optional avg As Variant) As Variant
到
Function StDev(rng As String, Criteria1 As Variant, Criteria_Rng1 As String, Optional avg As Variant) As Variant
快速检查所以要小心,我可能错过了一些东西。