2010 VBA - Pass Type as parameter

China☆狼群 提交于 2020-06-26 06:08:01

问题


I have a situation where i want to pass a object Type as a parameter for a comparison logic.

Example:

Sub Some (val as Control, typ as Type, ....)
   ...
   if typeof val is typ then
      ...
   end if
   ...
End Sub

I have found myself doing this logic pattern in multiple methods and want to condense the logic into one location instead of multiple spots, for simplification.

Is this the correct way of validating this type of structure or is there a better way of doing such things?


回答1:


That didnt take long

If you want to abstract a comparison to be generic this should get you to the right logic.

Public Sub CompareType(val as Control, typ as String)
   ...
   if TypeName(val) = typ then
      ...
   end if
   ...
End Sub

Basically pass the object (val), can be variant if you want to take one step up of abstraction, and then if you know what the String value that will be returned for that Type then pass it as a String value

Working Example:

In code run:

...
AutoSizeControl CurrentDb, frm, "Textbox"
...

Module Declaration:

Public Sub AutoSizeControl(ByRef db As Database, ByRef frm As Form, typ As String)
    Dim ctl As Control, i As Integer
    For i = 0 To (frm.Controls.Count - 1)
        Set ctl = frm.Controls(i)
        If TypeName(ctrl) = typ Then
            ctl.ColumnWidth = -2
        End If
    Next
End Sub

Hope this helps anyone else that may need such abstraction.



来源:https://stackoverflow.com/questions/12007364/2010-vba-pass-type-as-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!