2012-09-12 86 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