函数返回一个包含返回类的函数的类

我正在研究一个面向对象的Excel加载项来从我们的ERP系统的数据库中检索信息。 这是一个函数调用的例子:

itemDescription = Macola.Item("12345").Description

Macola是一个负责数据库访问的类的实例。 Item()是Macola类的一个函数,它返回一个ItemMaster类的实例。 Description()是ItemMaster类的一个函数。 这一切工作正常。

项目可以存储在多个位置,所以我的下一步是做到这一点:

quantityOnHand = Macola.Item("12345").Location("A1").QuantityOnHand

Location()是ItemMaster类的一个函数,它返回ItemLocation类的一个实例(理论上来说,无论如何)。 QuantityOnHand()是ItemLocation类的一个函数。 但由于某种原因,ItemLocation类甚至没有被初始化。

 Public Function Location(inventoryLocation As String) As ItemLocation Set Location = New ItemLocation Location.Item = item_no Location.Code = inventoryLocation End Function 

在上面的示例中,variablesitem_no是ItemMaster类的成员variables。

奇怪的是,我可以在非类模块中成功实例化ItemMaster类之外的ItemLocation类。

 Dim test As New ItemLocation test.Item = "12345" test.Code = "A1" quantityOnHand = test.QuantityOnHand 

有什么方法可以使我按照自己的方式工作吗? 我试图保持API尽可能简单。 所以它只需要一行代码来检索一个值。

每次你的函数引用Location时,它都会创build一个New ItemLocation(因为它会调用函数,像recursion一样),或者看起来如此。 也许你需要在函数内部隔离ItemMaster,像这样

 Public Property Get Location(inventoryLocation As String) As ItemLocation Dim clsReturn As ItemLocation Set clsReturn = New ItemLocation clsReturn.Item = "item_no" clsReturn.Code = inventoryLocation Set Location = clsReturn End Property 

我不知道为什么你使用一个函数而不是一个属性,但如果你有一个很好的理由,我相信你可以适应这个。 我也不知道item_no从哪里来,所以我把它做成了一个string。

你可以尝试分离出你的VBA代码中对象的声明和实例化。 我也会创build一个对象variables局部的函数,并在最后返回它。 尝试这个:

 Public Function Location(inventoryLocation As String) As ItemLocation Dim il As ItemLocation 'Declare the local object ' Set il = New ItemLocation 'Instantiate the object on a separate line ' il.Item = item_no il.Code = inventoryLocation Set Location = il 'Return the local object at the end ' End Function 

我不知道这是什么原因造成的,但是我记得VB6 / VBA在同一行代码中声明和实例化一个对象时有问题。 我总是将我的Dim从我的VBA中分离出来,分成两行。

我似乎无法重现这一点,但让我报告我做了什么,也许这将帮助你find你的问题。

这是Class1的代码:

 Public Function f() As Class2 Set f = New Class2 fp = 42 End Function 

这里是Class2的代码:

 Private p_ Public Property Let p(value) p_ = value End Property Public Property Get p() p = p_ End Property Private Sub Class_Initialize() Debug.Print "Class 2 init" End Sub Private Sub Class_Terminate() Debug.Print "Class 2 term" End Sub 

如果我去了眼前的窗口,input:

 set c1=new Class1 

接着

 ?c1.f().p 

我回头:

 Class 2 init 42 Class 2 term 

因此,一个Class2的实例被创build,它的属性'p'被写入和读取,但随后VBA会在该行执行后杀死它,因为没有variables对该实例有引用。

就像我说的,这跟你所描述的问题不符。 我可能错过了一些细节,但我希望这有助于。

编辑:

澄清,我的意思是我简单的例子调用“c1.f()。p”来对应你的

 quantityOnHand = Macola.Item("12345").Location("A1").QuantityOnHand 

但我更简单的例子工作得很好。 所以你现在有三个答案,相当于“需要更多的信息”,但这是一个有趣的小谜题。

如果您没有看到“ItemLocation”实例被创build,那么这是否意味着您没有看到类“ItemMaster”的“Location”方法的调用? 所以可能的问题是上传的“位置”代码。