我有一个集合(employees员工)含有name,id,office,和officeto领域.我需要在等间距列中打印出这些信息.所以我需要找到最长的字符串名称,office,officeto ...的长度,并添加空格以使列间隔相等.
我知道如何使用记录集将字段名称发送到函数中.所以我的问题是......是否可以通过使用变量(类似于rst![fieldname])来引用类属性(name,office,officeto).我试着把它设置成一个字段上的记录集循环,但它没有编译.错误是class.property未定义.
Public Function PropertyLen(ByVal Property As String, ByRef Employees As colEmployees) As Integer
'This function uses a passed in class property, and returns the len of the longest class property in collection
On Error GoTo ErrorHandler:
Dim Emp As clsEmployee
Dim intLen As Integer
Dim lngCount As Long
For lngCount = 1 To Employees.Count
Set Emp = Employees.Item(lngCount)
If Len(Trim(Emp.Property)) > intLen Then
intLen = Len(Trim(Emp.Property))
End If
Set Emp = Nothing
Next
FieldLen = intLen
ExitFunc:
'clean up
Set Emp = Nothing
Exit Function
ErrorHandler:
modErrorHandler.DisplayUnexpectedError Err.Number, Err.Description
Resume ExitFunc
End Function
Run Code Online (Sandbox Code Playgroud)
有一个clsSample用于测试的示例类模块:
Public Prop1
Public Prop2
Public Prop3
Public Prop4
Run Code Online (Sandbox Code Playgroud)
您可以使用本机VBA函数CallByName()按名称获取属性值:
Sub TestGetProperty()
Set objSample = New clsSample
objSample.Prop1 = "TEST"
Debug.Print CallByName(objSample, "Prop1", VbGet) ' TEST
End Sub
Run Code Online (Sandbox Code Playgroud)
如果您不想使用,CallByName()那么您可以使用jscript语法object[property]:
Sub TestGetProperty()
Set objSample = New clsSample
objSample.Prop1 = "TEST"
Debug.Print GetProperty(objSample, "Prop1") ' TEST
End Sub
Function GetProperty(objSample, strName)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
objHtmlfile.parentWindow.execScript "function GetProperty(sample, name) {return sample[name]}", "jscript"
End If
GetProperty = objHtmlfile.parentWindow.GetProperty(objSample, strName)
End Function
Run Code Online (Sandbox Code Playgroud)
BTW还有另一种类似的解决方案,允许将字符串计算到对象中,并通过类名创建新的类实例.
您可以创建一个包装函数,它接受一个对象和属性的字符串名称,并返回具有该名称的对象的属性。像这样的东西:
Function GetProperty(O As Object, property As String) As String
Dim s As String
property = LCase(property)
Select Case property
Case "name"
s = O.Name
Case "id"
s = O.ID
Case "office"
s = O.Office
Case "officeto"
s = O.officeto
End Select
GetProperty = s
End Function
Run Code Online (Sandbox Code Playgroud)
这大多未经测试(因为我不想实例化你的班级成员),但它能够在我评估时返回 Sheet1 的名称GetProperty(Sheets(1), "name")
| 归档时间: |
|
| 查看次数: |
4228 次 |
| 最近记录: |