2014-09-05 65 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