如何在VBA中动态引用对象属性

时间:2022-02-04 16:55:30

I'm trying to write a VBA function that counts the objects in a collection based on the value of one of the object's properties. I need the examined object property to be dynamic, supplied by the function parameters. I could use an if then statement, but that would have many, many elseif clauses, each with identical procedures, except the property name.

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

I'd like to avoid repeating my code over and over for each property name. Here's what I have so far.

我想避免为每个属性名称反复重复我的代码。这是我到目前为止所拥有的。

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

The issue I'm having is that the compiler is looking for the "f" property of t instead of the value-of-f property of t. The exact error is commented in the code block above. How do I use the value of f instead of "f" to reference the object property?

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

1 个解决方案

#1


8  

I believe you want to use the CallByName method CallByName MSDN Link

我相信你想使用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

#1


8  

I believe you want to use the CallByName method CallByName MSDN Link

我相信你想使用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