2012-09-12 40 views
0

我写一个VBA插件函数进行一系列的矩形舍入。在我的VBA方法中,我想检测包含公式/ VBA方法的单元格上是否有空单元格。但是,如果我在我的方法中使用ActiveCell Excel抱怨循环引用,并返回0而不是我的方法的返回值。示例方法:循环引用excel公式使VBA方法返回0

Function MovingAverageSmooth(r As Range, m As Integer) 
    ' returns a smoothed average using the 'rectangular' method 
    Dim cStart As Long, x As Long, total As Double, activeColumn As Long 
    Dim vc As Long, vr As Long, count As Double, beforeCount As Long, afterCount As Long 

    vc = r.Column 
    vr = r.Row 

    rStart = Max(1, vr - m) 
    currentValue = Cells(vr, vc).Value 
    activeColumn = ActiveCell.Column 
    For x = rStart To vr + m 
     If Application.IsNumber(Cells(x, vc).Value) Then 
      total = total + Cells(x, vc).Value 
      count = count + 1 
      If Application.IsNumber(Cells(x, activeColumn).Value) Then 
       If x < vr Then 
        beforeCount = beforeCount + 1 
       End If 
       If x > vr Then 
        afterCount = afterCount + 1 
       End If 
      End If 
     End If 
    Next 
    MovingAverageSmooth = total/count 
    If afterCount = 0 Or beforeCount = 0 Or count = 0 Then 
     MovingAverageSmooth = currentValue 
    End If 

End Function 
+2

公式如何知道ActiveCell在计算时的内容?看起来这可能会导致问题。 –

+1

@DougGlancy说的可能是你的问题(以及ActiveColumn引用)。这就是说,这是真正难以理解的代码,因为1)你没有评论,2)你的变量名没有太多含义。 – enderland

+0

那么我怎么知道当我的方法被调用时什么单元格是公式? – Martlark

回答

1

我认为这将适用于您。正如我的评论中提到的,Application.Caller返回调用函数的单元格:

Function MovingAverageSmooth(r As Range, m As Integer) 
    ' returns a smoothed average using the 'rectangular' method 
    Dim cStart As Long, x As Long, total As Double, activeColumn As Long 
    Dim vc As Long, vr As Long, count As Double, beforeCount As Long, afterCount As Long 

    vc = r.Column 
    vr = r.Row 

    rStart = Max(1, vr - m) 
    currentValue = Cells(vr, vc).Value 
    activeColumn = Application.Caller.Column 
    For x = rStart To vr + m 
     If Application.IsNumber(Cells(x, vc).Value) Then 
      total = total + Cells(x, vc).Value 
      count = count + 1 
      If Application.IsNumber(Cells(x, activeColumn).Value) Then 
       If x < vr Then 
        beforeCount = beforeCount + 1 
       End If 
       If x > vr Then 
        afterCount = afterCount + 1 
       End If 
      End If 
     End If 
    Next 
    MovingAverageSmooth = total/count 
    If afterCount = 0 Or beforeCount = 0 Or count = 0 Then 
     MovingAverageSmooth = currentValue 
    End If 
End Function 
+0

这会起作用,但有一个重要的缺点:虽然“调用者”允许访问传入函数的单元以外的单元,但对这些单元的更改将不会触发重新计算。通常最好传入参考所有相关范围的函数参数。 –

+0

这并没有解决循环参考问题。看来Application.IsNumber(Cells(x,activeColumn).Value)方法导致了这个问题。我放弃这种方法,直到我学到更多东西。 – Martlark