如何dynamic引用VBA中的对象属性

我正在尝试编写一个VBA函数,根据对象属性的值来计算集合中的对象。 我需要被检查的对象属性是dynamic的,由函数参数提供。 我可以使用一个if then语句,但是这将会有很多很多的elseif子句,除了属性名外,每个子句都有相同的过程。

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

 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 tf = 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”来引用对象属性?

我相信你要使用CallByName方法CallByName MSDN链接

 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