|
|
It is common to have object variables that may be needed throughout an application's lifetime. One would perhaps use a Public Variable but this comes with the problem of accessing the variable without properly initializing or maybe accessing it after it was closed or reset. To ensure that we can always depend on the object being available, regardless of when and how we access the object. A common candidate for this is ADO's Connection object but it needs not be restricted to just ADO Connection objects. The example below uses ADO Connection but this can be adapted for any other object variables with some modifications. CODE ' Code courtesy of UtterAccess Wiki
' http://www.utteraccess.com/wiki/index.php/Category:FunctionLibrary ' ' You are free to use it in any application, ' provided this copyright notice is left unchanged. Public Function MyConn As ADODB.Connection() 'We need a variable to hold the object in memory between calls Static conn As ADODB.Connection 'Check if the object is ready for use. If not, initalize it. 'We use Select Case so we do not get an error that would occur 'for a If/Then statement Select Case True Case conn Is Nothing, conn.State = adStateClosed 'The variable needs to be initialized Set conn = New ADODB.Connection conn.ConnectionString = "<your connection string>" 'Set other parameters as necessary End Select 'Return the object. Set MyConn = conn End Function By using the function, we can be always certain that we will always get an initialized object without needing to add checks in all calling code. Note that the error handling is not included and is left up to you to add/customize as you see fit. Enjoy!
|
| This page was last modified 09:41, 6 April 2011. This page has been accessed 1,104 times. Disclaimers |