Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  HOME    TRACKER    Visual Basic

Class_initialize And Class_terminate

what is the usual code that put at class_initialize and class_terminate event?

View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
I've got a Class with a Class_Terminate Sub and that Sub calls a several cleanup methods like a Log write, this call works fine in ASP environment but it's wasn't call from a VB environment at all when I set an object to Nothing, well it's happen in debug mode, I wasn't test in a fully compiled way.

That anyone knows why this happens?

Class_Terminate Not Firing..
I've got a class (which forms a tree structure) which contains other instances of itself as members, essentially Parent and Child properties.. and also a Root (so every node has instant access to the first node).

Now.. I've discovered that my Class_Terminate event is not firing when I do

Set objMine = New clsMine
'... do stuff with the class
Set objMine = Nothing ' Doesn't terminate the class
I think this is because there are still "things" (the children for example) which are referencing the object and are still "in scope" so it doesn't terminate...
So I've lost access to the root object, and all the children as well, which becomes a fairly hefty "memory" leak... (7 minutes the IDE sat there "THINKING" when I quit the app)

So far I've solved it by adding a Kill method.. which descends through the tree, setting the Parent and Root references to nothing and the child references as well... and I've got my terminates back....

But is there an easier way of acheiving this, 'cos it does take "some time" to descend through the whole tree killing off all the references...

Is there something simple I've missed??

Cheers TIA

Class_Terminate Event Is Not Executing
I'm having some problems with the Class_Terminate event in my class collection called 'Things'. It doesn't appear to be executing when I press the 'stop' button to kill the application. To test this, you need to put a name(string) in the first textbox, then put a size(integer) in the 2nd text box, then click 'Add to Collection'. Then click 'Add to List' to add to list box; this also adds contents from data.txt. When the app terminates, it is supposed to write what you've added to the collection, back to the text file, but its not happening. Anybody have any thoughts? TIA.

Problem With Class_Terminate Event...
I have an ActiveX EXE...This has a a class module called User...When a new instance of User is created it is added to a collection in the common module, which contains Sub Main. It is added using:

VB Code:
Private Sub Class_Initialise()   AddUserToCollection MeEnd Sub

This works well and am happy with the outcome. The problem is in the Class_Terminate event:

VB Code:
Private Sub Class_Terminate()   RemoveUserFromCollection KeyEnd Sub

When stepping though the code in VB's IDE it works fine and the whole application runs like clockwork, but once compiled it refuses to fire off the Class_Terminate event when a reference to it is destroyed

In the IDE is works.
Once compiled it doesn't...


Why Is Class_Terminate Method Being Invoked?
I'm trying to convert some VBA routines in an Excel 2000 workbook to use
objects instead of global varaibles. I've defined a class module with
the following (excerpts):

(from SheetMetrics class module)
Private m_HoldingSheetName As String
Private m_rngFundSymbols As Range
Option Explicit
Private Sub Class_Initialize()
m_HoldingSheetName = ""
End Sub
Private Sub Class_Terminate() <==being invoked in error
Set m_rngFundSymbols = Nothing
End Sub
Public Property Let SheetName(SheetID As String)
If Not SheetID = "" Then
m_HoldingSheetName = SheetID
End If
End Property
Public Property Get SheetName() As String
SheetName = m_HoldingSheetName
End Property
Public Property Let SymbolRange(SymbRange As Range)
Set m_rngFundSymbols = SymbRange
End Property
Public Property Get SymbolRange() As Range
Set SymbolRange = m_rngFundSymbols
End Property

In a worksheet code module I attempt the following (PECategories is a
named range on the worksheet):

Dim AcctSheet(4) As SheetMetrics <== class module above

Set AcctSheet(1) = New SheetMetrics
Set AcctSheet(2) = New SheetMetrics
Set AcctSheet(3) = New SheetMetrics
Set AcctSheet(4) = New SheetMetrics

AcctSheet(1).SheetName = "PE Holdings"
AcctSheet(1).SymbolRange = Range("PECategories") <==problem

When the last statement above SHOULD execute, the
Class_Terminate method kicks off instead.

I'm stumped - would be grateful for any suggestions what is causing this
to happen...

Class_Terminate Not Being Called (CSurface Class)
I'm working on my surface class and I have a problem.
My goal is to create an instance of this class and add it to a collection with one function call.
The reason for the collection is to set them all to = nothing when I'm done.
The problem is the Class_Terminate sub isn't being called.

Here's an example:

'CSurface Class

Private dds as DirectDrawSurface7
Private ddsd as DDSURFACEDESC2

Public Sub CreateSurfaceFromFile(FilePath As String)
'Creates a surface from file and sizes rect based on size of picture
Set dds = Nothing
Set dds = DD.CreateSurfaceFromFile(FilePath, ddsd)
rSurface = GetRect
ColorKey.low = vbMagenta
ColorKey.high = vbMagenta
dds.SetColorKey DDCKEY_SRCBLT, ColorKey
End Sub

Private Sub Class_Terminate()
Debug.Print "terminating surface"
Set dds = Nothing
End Sub

'This function is global and used to create an instance of CSurface then add it to a collection.

Public Function CreateSurfaceFromFile(FilePath As String) As CSurface
'Creates an instance of a CSurface class and adds it to a collection
Dim dds As CSurface
Set dds = New CSurface
dds.CreateSurfaceFromFile FilePath
colSurfaces.Add dds
Set CreateSurfaceFromFile = dds
End Function

Public ddsTest as CSurface 'GLOBAL


Set ddsTest = CreateSurfaceFromFile(App.Path & "dataBox.bmp")
For Each dds In colSurfaces
Set dds = Nothing

Setting "dds = Nothing" should call Class_Terminate for the instance of CSurface, therefore printing "terminating surface" in the debug window and killing the surface. But this doesn't happen.

Any ideas?

Different Between Dim And Private + Run The Code At Class_terminate Procedure
Hi to all gurus out there,

1. Can anyone explain the differnt dim and private in a coding?

To me it seem no different at all.

2. I need to delete a file upon exiting an application. To do this, I wrote the code in the Class_terminate procedure. The object is created once the application is activated.

A command button is created for exiting the program, which has the code as follow:

unload me

The application is successfully terminated upon activation of the command button but the file is not deleted. It seem to me the object is destroyed but the class_terminate procedure is not executed.

Could anyone explain this and what code should i used in the command button to successfully terminate the file?

Thank you very much

I've hardly written any vb in the last year or so, and I've forgotten something....

Can you pass parameters to the default constructor for a class?


The class constructor (for class cTrain):

Private Sub Class_Initialize(sFlowTag As String, sFieldTag As String)
'Do some stuff
End Sub

Then declare an instance:

Dim Train1 As cTrain

Sub test()
Set Train1 = New cTrain("AFIC-0160/A","AZSC-0111")
End Sub

IIRC, don't I have to set a new instance of the class, THEN call some other initialisation routine?


Dim Train1 As cTrain

Sub test()
Set Train1 = New cTrain
End Sub

Class_Initialize() Help
I have 3 classes that all do about the same thing. The only difference in them would be a store procedure that they call. I am still pretty new at creating classes, but on the Class_Initialize(), can you initalize a class passing it a variable so that the class knows which stored procedure to use for that instance?


Class_Initialize(StoreProc as String)

Set cMyClass = new clsSomeClass(SomeStoreProc)

Thanks for any help or advise you can provide. Trying to slim down some code that we have.

Is it possible to pass a variable to this sub in order to setup your class in a different way depending on the value that was passed?

Also when does this sub fire?

Here: Dim undo As clsStack
Or Here: Set undo = New clsStack



I'm creating simple Class only for study how to work with classes.
So i'm creating simple version of command buton (not ocx but class).
So if i want to draw something, i need to know where to draw.

For example i have frmMain, on which i want to draw this button, so i do this:

Option Explicit
Private WithEvents Button1 As clsButton

Private Sub Form_Load()
Set Button1 = New clsButton

End Sub

My class (clsButton) must get frmMain.hdc.
What code do i need to write into Sub Class_Initialize to get hdc of frmMain?

Probably there is something how to know where this class was initialized (i mean Set Button1 = New clsButton)

Can someone help me?

Hi all,

Can I pass any parameter to the Class_Initialize event in a class

if not please suggest me any method to pass.

my requirement is i need a value in the Class_Initialize to manuplate my logic, i am using asp and vb dll communication

Thanks in Advance ...

Satish Kumar J.....

Class_Initialize() Question
Hi there! I've got an easy question for you!

I've already wrote these 2 subs:

VB Code:
Private Engine As SAS_ULENGINELib.Ulengine Private Sub Class_Initialize()'Creation of the engine'Benjamin Moffet 2006-06-14  Set Engine = New SAS_ULENGINELib.Ulengine    'Initialize the Engine  EngineInitialize End Sub Private Sub Class_Terminate()'Disallows the memory used by the Engine   Set Engine = Nothing End Sub

But, the problem is that these 2 subs show in the General sub drop down box instead of having Class on the left drop down and Initialize/Terminate on the right.

How do I correct this??

Parameter To Class_initialize
how do i give a parameter to the class_initialize?


Private Sub form_load()
filename = "c:dbSteden.mdb"
Set mclsDBAccess = New ClsDbAccess


Public Sub Class_initialize()
Dim cn As New ADODB.Connection

Set m_DBConnection = New ADODB.Connection
m_DBConnection.Open _
"Provider=Microsoft.Jet.OLEDB.3.51;" & _
"Persist Security Info=False;" & _
"Data Source=" & "c:dbsteden" 'this must be the parameter from the form

Set rs = New Recordset
rs.Open "select * from landen", m_DBConnection, adOpenStatic, adLockOptimistic

End Sub

Class_initialize Is Not Getting Fired

I use a VB DLL in which I have written code to form DB Connection String (read from the registry)

This logic is written in a subroutine (public) in a modlue of the project.

I call this subroutine from Class_Initialize of the Class File.

When instantiate this DLL in another project and call another routine in the DLL (of the same class) I expect the Class_Initialize to have fired first and the connection string to be ready. However this does not happen.

WHen I put a trace (basically write few lines into a text file at each of the routines), I find that the routine that I call from the DLL is getting fired but not the Routine to be called from Class_Initialize.

What could be wrong?

Thanks in advance.


Doubt On Class_Initialize
Hi All,

Can somebody tell me when does this Class_Initialize method get invoked in an Active X Dll.
This is what I did.
I placed a message box in Class_Initialize.
I added one more function and placed a message box in it to.
I made it a dll.
Added this dll as a reference in another project.
In this project
I declared this


Dim obj as new project.class

In the form load I called the Dlls method.

I expected to get the message box at the line where we create an instance of the above mentioned class but I am getting two message boxes when I call the function of that class.

So why is this Class_Initialize not invoked till a function of this class is called.
Is this Class_Initialize not the same as a Custructor in C++ which gets called when we say new object().

Please Clarify.


Is It Possible To Pass A Value To The Class_Initialize() Event?
I'm trying to figure out a way to open a connection to a server in the class initialize event of my dll. I'm opening the class within an Access db and I would like to pass my server connection to the class. Passing in the initialize event seems like the easiest way to do it, but I think I may recall that it's not allowed. Can someone verify this? If not, anyone have a suggestion on how to do this?

How To Initialize Things To Null In Class_Initialize()
Hi all:
I would like to know what the correct syntax is for initializing everything to NULL in Class_Initialize() i.e. I have to following

private obj1 as Object1
private obj2 as Object2

private sub Class_Initialize()
set obj1 = null
set obj2 = null
end sub

is the above ligitimate??? the reason i want to do so, is..later on i have a function
that checks if obj1 is null, if it is null, it will instantiate it, otherwise, it will just return obj1.

pelase let me know.
Many thanks

Opening An Access 2000 Database With VB6 Class_Initialize
I have been given a program written by another engineer some time ago and have been asked to modify it to use access 2000 and implement a password on the database so unauthorized users cannot get into the database without going through the VB6 front end. The following is the current code for opening the database in the VB6 code:

' Database and recordset objects
Private mdb As Database
Private mrs As Recordset

Private Sub Class_Initialize()

' open the database and recordset

Dim strDBName As String

strDBName = "\Besccr2prdatabaseOOPRFolder.mdb"

Set mdb = DBEngine.Workspaces(0).OpenDatabase(strDBName)

' Open the recordset.
Set mrs = mdb.OpenRecordset("PR_Table", dbOpenTable, dbSeeChanges, dbOptimistic)

' Raise an error if there is no data
If mrs.BOF Then
RaiseClassError ErrNoRecords
End If

' fetch the first record to the properties
PRData.Caption = "PR Datebase Entry Form, Number of records (" + Str(mrs.RecordCount) + ")"
End Sub

When I try this code with the access 2000 database without security it doesn't get any data from the database. How do I modify the code to allow me to acces the database and set the password in the connect string.

Do I Need To Declare Class As Public Or Declare Class_initialize As Public?
I have a ActiveX exe project and a standard project. My standard project reference ActiveX exe project.
To make it simple, I have one class module in the ActiveX exe project and I need to create an instance of the class in a new thread in the Standard project. These are how I've been tring:
In the standard exe:
Dim objMyClass As ProjectName.MyClass
Set objMyClass = CreateObject(ProjectName.MyClass);

I get the object successfully ONLY IF I have class_initialize in MyClass as Public or I have THIS LINE at the beginning of my MyClass module
Class MyClass As MyClass

I'm not sure how vb6 make a class publicly creatable and I don't know why what I tried works. I just guess and that works for me. I'd like to know WHY if anyone can help me really appreciate it. I've checked MSDN but no luck until now. Thanks all.

Copyright 2005-08, All rights reserved