Excel VBA:属性让程序没有定义和财产取得程序没有返回一个对象
我有一个Client
类。 在那个class级里面有一个数组losses
。 首先,我创build并填充客户端的一个clientsColl
数组。 然后,对于该arrays中的每个客户端,我填充它的losses
数组。
然后,我尝试打印debugging每个客户的losses
的第一个元素。 然而,它没有工作和Property let procedure not defined and property get procedure did not return an object
错误出现。
同时,如果我只是试图为第一个客户端显示第一个losses
元素,而没有任何循环,那么它工作正常:
Dim clientsColl() As Client clientsColl = getClients(dataWorkbook) Dim clientCopy As Variant Debug.Print "first: " & clientsColl(1).getLosses(1) 'works fine For Each clientCopy In clientsColl Debug.Print "in for each: " & clientCopy.getLosses(1) 'error here Next
在Client
类中:
Public Property Get getLosses() getLosses = losses End Property Private losses() As Double
如何填充losses
数组:
Public Sub calculateFinancialResult() ReDim losses(1 To simulationCount) ReDim profits(1 To simulationCount) Dim i As Long For i = 1 To simulationCount If outcomes(i) = 1 Then losses(i) = totalLoss ... Else ... End If Next End Sub
为什么会发生这种情况,以及如何解决?
编辑:更多的主要分:
For Each clientCopy In clientsColl clientCopy.setSimulationCount = globals("SIMULATION_COUNT") ... clientCopy.calculateFinancialResult ... Next
编辑:
同时一个简单for
循环工作正常:
Debug.Print "first: " & clientsColl(1).getLosses(1) For tempCount = LBound(clientsColl) To UBound(clientsColl) Debug.Print "in for each: " & _ clientsColl(tempCount).getLosses(1) Next
您的getLosses
属性不会带有参数,所以您的语法实际上是错误的,尽pipeVBA在早期绑定时可以应付它。 你应该使用:
Debug.Print "first: " & clientsColl(1).getLosses()(1) 'works fine For Each clientCopy In clientsColl Debug.Print "in for each: " & clientCopy.getLosses()(1) 'error here Next
总结评论中提到的内容:
当您尝试复合属性时,您的问题(错误451)经常发生。 为了表示这种情况,我们可以使用任何具有属性的对象的任何结构。
让我们用集合数组来模拟它:
Option Explicit Sub Test() Dim Arr As Variant Dim Col As Collection Dim i As Long Dim j As Long ReDim Arr(1 To 10) For i = 1 To 10 Set Col = New Collection For j = 1 To 10 Call Col.Add(j) Next Set Arr(i) = Col Next On Error Resume Next Debug.Print Arr(1).Item(1) Debug.Print Arr(1).Item()(1) On Error GoTo 0 End Sub
你的问题源于你将属性视为属性。 在不太复杂(或者当你的数组被明确声明为类实例的数组)的时候,它的工作原理是由于早期的绑定。 但是,当事情变得更复杂 – 这是失败的,因为你的财产只是另一个function。
因此,为了实现你想要的,你应该用另外一对圆括号来明确地调用它。