【问题标题】:How to dynamically reference an object property in VBA如何在 VBA 中动态引用对象属性
【发布时间】:2014-09-05 17:58:33
【问题描述】:

我正在尝试编写一个 VBA 函数,该函数根据对象属性之一的值对集合中的对象进行计数。我需要检查的对象属性是动态的,由函数参数提供。我可以使用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 t.f = s Then x = x + 1 ' Compiler throws "Method or data member not found."
Next t

getTicketCount = x
End Function

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

【问题讨论】:

  • Ticket 有多少个属性?这并不优雅,但您可以使用Select Case f 并让案例具有不同的属性。
  • 您遇到的具体错误是什么?
  • 问题已编辑以澄清。编译器抛出一个错误,因为当它应该寻找属性值-f时它正在寻找属性“f”。传递的属性字符串确实存在。对象本身有几十个属性,在单独的 case 子句中对它们进行编码正是我想要避免的。

标签: vba excel object


【解决方案1】:

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

【讨论】:

  • 是的!我在 MSDN 上寻找这样的功能,但找不到。谢谢!
  • 此答案还显示了如何使用 CallByName 设置属性。文档对此并不完全清楚,尤其是关于何时使用 vbSet 与 vbLet。 stackoverflow.com/questions/5706791/…
猜你喜欢
  • 2018-08-13
  • 1970-01-01
  • 2020-10-07
  • 2011-12-06
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 2019-09-01
相关资源
最近更新 更多