VBA:通过子例程调用参数转发类型

时间:2017-04-26 08:17:37

标签: vba types

我第一次来这里。

编码VBA,相当陌生。

=============================================== ==================

目标:将坐标输入到对象/类中。

...表示"等等"

现在解决方案:使用数组,例如

=============================================== ==================

的Class1:

sub start()
    Dim c2 as new Class2
    Dim points() as Double
    Redim points(7)
    point(0) = ...
    ...
    point(7) = ...
    cs.draw points
end sub

等级2:

public Sub draw(points() as double)
    ...
end sub

=============================================== ==================

问题是:难以跟踪巫婆阵列槽代表一个特定的兴趣值。

我想做的事情是:

第1课:

Type Properties
    length As Double
    keygripp As Double
    diameter As Double
    tapdiameter As Double
    steerlength As Double
    distance As Double

    plateau As Double
End Type


sub start()
    Dim c2 as new Class2
    Dim points as Properties
    point.length = ...
    ...
    point.plateau = ...
    cs.draw points
end sub

等级2:

public Sub draw(p as Properties) '<---- Class 2 also need access to properties?
    ...
    doCoolStuff(p.length)
    doOtherCoolStuff(p.keygripp, p.diameter)
    ...
end sub

我是否以某种方式声明了Type Properties全局,以便class1和class2都知道它是什么?

问候// Martin

1 个答案:

答案 0 :(得分:0)

据我了解您的问题,您可以创建例如Point类并在集合中使用它,然后将此集合的实例传递给Draw方法。 HTH

注意:名称Point与您问题中的Properties名称相对应。

  

点类模块

Option Explicit

Private m_length As Double

Public Property Get Length() As Double
    Length = m_length
End Property

Public Property Let Length(ByVal vNewValue As Double)
    m_length = vNewValue
End Property

' Tha same as by lenght for the next properties
'    keygripp As Double
'    diameter As Double
'    tapdiameter As Double
'    steerlength As Double
'    distance As Double
'    plateau As Double
  

处理器类模块

Option Explicit

Public Sub Draw(pts As VBA.Collection)
    Dim p As Point
    For Each p In pts
        ' ...
        ' doCoolStuff p.Length
        ' doOtherCoolStuff p.keygripp, p.diameter
        ' ...
    Next p
End Sub
  

标准模块

Sub Start()
    Dim pt As Point
    Set pt = New Point
    pt.Length = 123
    ' pt.plateau = ...

    Dim points As VBA.Collection
    Set points = New VBA.Collection
    points.Add pt

    Dim proc As Processor
    Set proc = New Processor
    proc.Draw points
End Sub

如果您希望保留用户定义的类型,则在标准模块中声明类型,然后将其与数组一起使用(UDT不能与VBA.Collection一起使用)。

  

标准模块

Type PointType
    length As Double
    keygripp As Double
    diameter As Double
    tapdiameter As Double
    steerlength As Double
    distance As Double
    plateau As Double
End Type

Sub start()
    Dim pt As PointType
    pt.length = 555

    Dim pt2 As PointType
    pt2.length = 666

    Dim pts(1 To 2) As PointType
    pts(1) = pt
    pts(2) = pt2

    Dim proc As Processor
    Set proc = New Processor
    proc.Draw pts
End Sub
  

类处理器

Public Sub Draw(pts() As PointType)
' use for-next isnatead of for-each-next here