2017-06-09 41 views
1

我很努力地使用我在VBA中构建的函数。我尝试在另一个表格中使用它,这是我在函数内引用的那个表格,但是我得到循环引用错误。任何人都可以帮我吗?这是我第一次在VBA中编写代码,所以请理解这些错误是否有趣。错误来自函数的循环引用VBA

Function Dividend(row As String, col As Date) As Variant 
Dim Table As Range 
Dim Blgdata() As Variant 
Dim v As Integer 
Dim h As Integer, var As Date 

v = 666 
h = 27 

Sheets(3).Activate 
Set Table = Range(Cells(179, 1), Cells(844, 27)) 
Debug.Print Table.Address 
ReDim Blgdata(1 To v, 1 To h) 
Blgdata = Table 




Dim i As Integer, j As Integer 


'For i = 1 To 666 
    ' For j = 1 To 26 
    '  Debug.Print Blgdata(i, j) 
    '  If Blgdata(i, j + 1) = 0 Then 
    ' Exit For 
     ' 
     ' End If 

    'Next j 
'Next i 


For i = 1 To v Step 7 
    If Blgdata(i, 1) = row Then 
            For j = 3 To h 

            var = Blgdata(i + 1, j) 
            'Debug.Print var 

            If (var = col) Then 
            Dividend = Blgdata(i + 4, j) 
            Exit For 
            End If 

            If j = h Then 
            Dividend = "-" 
            Exit For 
            End If 

            If Blgdata(i, j + 1) = 0 Then 
            Exit For 
            End If 

            Next j 


    End If 

Next i 

End Function 
+0

哪一行代码会产生错误?并且是工作表或模块中的上述代码(如果表是哪一个)? –

+0

不相关,但在签名中'row As String,col as Date'只是看起来不正确。事实上,这完全是令人困惑的 - 将来你会看到那个代码说“WTF?!”在几个月后。行/列将被合理地预期为指向行/列索引的“Long”整数。 –

+0

您可能想要使用[Rubberduck](http://rubberduckvba.com/indentation)(免责声明:我管理该开放源代码项目)等工具来帮助您正确缩进。 –

回答

0

我写的第一个关于编写vba函数的建议是让你的函数有机会做比你为它写的更多的工作。例如,而不是你的

sheets(3).Activate 

你可以使用使用Activesheet或更好的,传递函数的范围,你想要行事。

与V和H变量同样的事情,也许使用

h = inputrange.columns.count() 

功能,让您可以通过不同大小的范围。

这一切都说,我不能真正重现或测试您的循环引用错误,因为它被写入只在您的特定工作表上工作,我没有。

作为一般性建议,如果您确实需要循环引用(如需要迭代解决方案的问题),您可以检查enable iterative calculation复选框,它将允许循环引用。

好运,

埃德加。