简体   繁体   中英

VBA Successive Class object reference

I am working on a VBA project that can be used to calculate properties of gas flow through a duct system. The duct system consists of a number of Segments (a VBA class; clsSegment) stored in a Collection stored by the class clsSegments.

Each Segment has a Duct class (clsDuct) which consists of an Inlet and Outlet defined by the class clsDuctDim.

If I want Segment no. 2 Inlet Duct to inherit the properties of Segment no. 1 Outlet Duct I use:

set Segments(2).Duct.Inlet = Segments(1).Duct.Outlet

This works.

Likewise I can choose to use the inlet duct as outlet duct by:

set segments(2).Duct.Outlet = segments(2).Duct.Inlet

Now if I want Segment no. n+2 to do the same I write:

set Segments(3).Duct.Inlet = Segments(2).Duct.Outlet
set Segments(3).Duct.Outlet = Segments(3).Duct.Inlet

This causes Segment no 3 to actually point to Segment no. n. If I break the reference between Segments 2 and 1, Segment 3 still points to Segment 1. This is not what I want. I want that Segment 3 is pointing to Segment 2. I guess what I am trying to do is to point to a pointer, rather than point to the actual memory location where segment 1 data is stored.

How can this be achieved?

There is no direct way to do that in the VBA. An easy workaround is to add a Copy or Clone method to your clsSegment Class.

Segments(3).Copy Segments(2)

Sub Copy(segement As clsSegment)
    Me.Duct.Outlet = segement.Duct.Inlet
    Me.Duct.Inlet = segement.Duct.Outlet
End Sub

The can automate changes by adding custom events and setting references to parent object. I'm not sure how this would apply to your system but here is a simple notification system.

clsSegment

Enum DuctEvents
    deInletRemoved
    deOutletRemoved
End Enum

Public Sub DuctChanged(e As DuctEvents)
    'Do Something
End Sub

Class clsDuctDim

Public Event DuctRemoved()

Private Sub Class_Terminate()
    RaiseEvent DuctRemoved
End Sub

Class clsDuct

Public parent As clsSegment
Private WithEvents Inlet As clsDuctDim
Private WithEvents Outlet As clsDuctDim

Private Sub Inlet_DuctRemoved()
    parent.DuctChanged (deInletRemoved)
End Sub

Private Sub Outlet_DuctRemoved()
    parent.DuctChanged (deOutletRemoved)
End Sub

I added an Enumeration to the clsSegment class to clean up the messaging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM