2014-09-05 63 views
1

我正在尝试编写一个VBA函数,该函数可以根据对象的某个属性的值来计算集合中的对象。我需要被检查的对象属性是动态的,由函数参数提供。我可以使用if then声明,但是这将有许多很多elseif子句,每个子句都具有相同的过程,但属性名称除外。如何动态引用VBA中的对象属性

我想避免重复我的代码重复每个属性的名称。这是迄今为止我所拥有的。

Private Function getTicketCount(c As Collection, f As String, s As String) _ 
As Long 
' @param c: collection of Ticket objects. 
' @param f: property to filter. 
' @param s: filter string. 
' 
' Function returns number of tickets that pass the filter. 

Dim x As Long 
Dim t As Ticket 

x = 0 

For Each t In c 
    If t.f = s Then x = x + 1 ' Compiler throws "Method or data member not found." 
Next t 

getTicketCount = x 
End Function 

我遇到的问题是编译器正在寻找t的“f”属性而不是t的f值属性。确切的错误在上面的代码块中注释。我如何使用f的值而不是“f”来引用对象属性?

+0

多少性能不'Ticket'有哪些?这不是优雅的,但你可以做'选择案例f',并让案例成为不同的属性。 – Degustaf 2014-09-05 18:29:38

+0

你得到的错误究竟是什么? – 2014-09-05 18:35:52

+0

编辑澄清的问题。编译器会抛出一个错误,因为当它寻找属性值-f时,它正在寻找属性“f”。传递的属性字符串确实存在。该对象本身具有几十个属性,并且将它们全部在单独的条件语句下编码正是我想要避免的。 – T6J2E5 2014-09-05 18:51:25

回答

7

我相信你想使用CallByName方法CallByName MSDN Link

Private Function getTicketCount(c As Collection, f As String, s As String) _ 
As Long 
' @param c: collection of Ticket objects. 
' @param f: property to filter. 
' @param s: filter string. 
' 
' Function returns number of tickets that pass the filter. 

Dim x As Long 
Dim t As Ticket 

x = 0 

For Each t In c 
    If CallByName(t, f, VbGet) = s Then x = x + 1 ' Compiler throws "Method or data member not found." 
Next t 

getTicketCount = x 
End Function 
+0

是的!我正在MSDN上寻找这样的功能,但找不到它。谢谢! – T6J2E5 2014-09-05 21:00:49

+0

该答案还显示了如何使用CallByName设置属性。文档并不完全清楚,特别是在何时使用vbSet vs vbLet。 http://stackoverflow.com/questions/5706791/how-do-i-use-variables-to-set-properties-in-vba-excel – 2017-04-01 15:48:42