我有自己的类型(类模块)名为stdFastenersScrews,它有许多属性,例如Diameter,Length,Supplier等...
我已将所有螺丝装入stdFastenersScrews的一个系列中。
现在我正在尝试创建搜索功能,它根据搜索条件返回新的Collection,但我不知道,如何将搜索条件(字符串)转换为stdFastenersScrews属性名称。我试过这样的事,但当然,它不起作用......
Public screws As Collection
Public Sub parseScrews()
Set screws = New Collection
'...
' Here are parsed data from Excel into screws collection
'...
Dim searchResult As Collection
Set searchResult = searchScrews("Diameter=3")
End Sub
Public Function searchScrews(condition As String) As Collection
Dim results As Collection: Set results = New Collection
Dim cond() As String: cond = Split(condition, "=")
If screws.Count > 0 Then
Dim screwData As stdFastenersScrews
For Each screwData In screws
If screwData.cond(0) = cond(1) Then
results.Add screwData
End If
Next
Else
Call MsgBox("Cannot found any data about screws", vbInformation + vbOKOnly)
End If
Set searchScrews = results
End Function
上面我有行
If screwData.cond(0) = cond(1) Then
我希望VBA采用screwData.Diameter(因为cond(0)=“Diameter”)而我真的不知道,怎么做。你知道吗?
答案 0 :(得分:0)
您可以添加searchScrews()
作为您班级的方法:
Public Function searchScrews(condition As String, screwsColl As Collection) As Collection
Dim results As Collection: Set results = New Collection
Dim cond() As String: cond = Split(condition, "=")
Dim var As Variant
If screwsColl.Count > 0 Then
Dim screwData As stdFastenersScrews
For Each screwData In screwsColl
Select Case cond(0)
Case "Diameter"
var = screwData.Diameter
Case "Length"
var = screwData.Length
Case "Supplier"
var = screwData.Supplier
Case Else
Exit Function
End Select
If var = cond(1) Then results.Add screwData
Next
Else
Call MsgBox("Cannot found any data about screws", vbInformation + vbOKOnly)
End If
Set searchScrews = results
End Function
然后在“主要”代码中使用它:
Dim searchResult As Collection
Dim stdScrew As New stdFastenersScrews '<--| declare a variable of your class and get a new instance of it, so that you can call its methods
Set searchResult = stdScrew.searchScrews("Diameter=3", screws) '<--| call your class method
这可能不是最优雅的解决方案,但它应该至少保持一致,因为你的类也拥有查询自己属性的规则