Good practice for using variables across a program? - vb.net

Is it good practice to declare variables to be used across a program in a Module then populate them in one form and use what you have populated to these variables in another form?
I plan on closing the population form after the data has been populated to the variables so I see this as the only method that would work.
Am I right in thinking that passing parameters from the population form to the display form wouldn't be appropriate in this situation, if even possible?

I guess it depends on your application and the kind of data you're talking about.
Think of a User Login form that saves the user information after logging in. You can then keep this information in a Module shared across your entire application because it's not expected to change during the session. So you can quickly check the Permission, the Role, the Username from all your program Forms.
On the other end if you're querying a database you are probably asking for the latest data available and you do that in the specific Form you're using, without the need to share it across other Forms in the program.

...on the other hand, there is nothing whatsoever that a module can do that cannot also be done with a class. For a UserLogin example, leaving it in a module does not make it easier to access:
Friend User As New UserLogin
' elsewhere:
theName = User.Name
thePass = User.Password
Meanwhile, a class can manage the info:
Class UserLogIn
Sub LoadData
Sub SaveData
Function GetLogIn ' display form, validate ID etc
Function ChangePassword
Private gfrm as New LogInForm
Friend Sub Display()
With gfrm
.IgnoreChange = True
.cboName.Text = Name
.cboName.Tag = Name
.txtURL.Text = Location
.txtUser.Text = UserName
.txtPW.Text = DES.DecryptData(_pass)
.txtHint.Text = PassHint
.txtNote.Text = Comment
.IgnoreChange = False
.DataChanged = False
.Show
End With
' store PW hashed or encrypted until needed...
' No one can change the PW except this class
Friend Property PassWord() As String
Get
Return DES.DecryptData(_pass)
End Get
Private Set(ByVal value As String) ' private setter
_pass = DES.EncryptData(value)
End Set
End Property
End Sub
Modules are simply not any easier to use, maintain, store or access data. They are considerably less powerful.

No, and yes.
Define a class or perhaps more than one to hold the data, pass that about. If by module you mean one of those .bas things with a bunch of primitive types in it, then that would be considered bad practice unless there was no practical alternative.
It's not expected to change was what you said, but if you use a bunch of global variables, you can expect them to be changed and it to be very hard to track down, when and why.
They'll be changed because it was convenient, or in error and you end up with an intermittent major PIA bug. A class with getters and setters on it's properties, and it can manage changes to it's members, so if some "fool" of programmer makes a slight mistake..
The other consideration is unit testing which would be a nightmare if you go the way you are thinking.

Related

Late Binding to a form's public variables

I have 20+ MDI forms with consistently named Public variables. When the child form closes a method on the MDI Parent is called passing Me as a generic form type. How can I access the public variables by name via the Form reference? I only need to read the variables. Of course the Variables() method does not exist...
Public Sub CleanupForm(ByVal frm As Form)
Dim sTable_Name As String = frm.Variables("TABLE_NAME") ' Public at form level
Dim cLock As clsRecLocks
cLock = frm.Variables("Rec_Lock")
cLock.DeleteThisLock()
'..
I've seen some posts on similar requests but most start out with "don't do it that way..." then go off in the weeds not answering the question. I concede it is poor design. I can't change all the calling forms in the short term so I need to use this approach.
VS2010, VB.Net, Win Forms, .Net 2.0
I was able to get to a simple variable using CallByName:
Try
Dim s As String = CallByName(frm, "TABLE_NAME", CallType.Get)
Stop
Catch ex As Exception
MsgBox(ex.Message)
End Try
On to the class object. Perhaps I can add a default Get for the class that returns the ID I need.
Default property won't work as the Locks object was not declared Public - at least for the CallByName() approach.
Can Reflection get to form level variables not declared Public? Seems like a security issue, but...
Can I get a "Parent" reference in the instantiated Locks class? i.e. A reference to the form that established the Locks object? I can change the clsRecLocks() class.
I found a property I could get to that told me the form was "read-only" and I can use that tidbit to delete the correct (or more correct - still not 100%) lock record. So the bug is 90% fixed. I think I need update all the forms with code that records the info I need to get to 100%.
Thanks to all!
Poor design but you can do this:
Public Sub CleanupForm(ByVal frm As Form)
Dim frmTest as object = frm
? = frmTest.TABLE_NAME
? = frmTest.Rec_Lock
End Sub
This will compile and if the variables exist, it will return them but if not, you get an error.
Converting to an interface after the fact is not that hard, you should do it now rather than later.

Global variable loses its value

On this Access form I am working on I have a global variable that take its value from another form on its Form_Load event. For some reason unknown to me the variable "loses its value" (becomes = "") after some time elapses or some event occurs. I have not been able to notice anything in particular that triggers this behaviour. Are global variables reset after some time of "inactivity" on the form ?
Here is how I set the global variables I am talking about:
Private Sub Form_Load()
'...
Set prev_form = Form_Identification.Form
PasswordSybase = prev_form.Password.Value & vbNullString
UserSybase = prev_form.UserID.Value & vbNullString
'...
End Sub
An alternate solution (Only 2007 and onwards) I've started using is TempVars instead of globals in the odd situation I "needed" something global. It's a collection and it persists for the duration of the application unless you explicitly release it. So in some cases I feel its more useful than globals and in some cases worse.
TempVars.Add myVarName, myVarValue ' To initialize
TempVars.Item(myVarName) = newVarValue ' To reference and assign a new value
TempVars.Remove(myVarName) ' To release
Quick search should show you more lot references, but I've included link to a basic one
http://blogs.office.com/b/microsoft-access/archive/2010/09/27/power-tip-maximize-the-user-of-tempvars-in-access-2007-and-2010.aspx
I do hope that visitors see this post, as it provides an important additional piece.
Even if you declare a variable globally, it appears that - in the event that you set that variable's value in a form module - that value is lost when you UNLOAD the form.
The solution (in my case) was as simple as replacing:
Unload Me
...with...
Me.Hide
The variables (and objects) that I set in that code module then retained their values through the entire lifetime of the application instance.
This may help:
https://accessexperts.com/blog/2011/01/12/multi-session-global-variables/
Juan Soto explains how to use a local table to keep variables and how to call them when needed. It may serve your purpose in 2000 since TempVars isn't an option. You could always delete the variables "on close" of the database so that UID and PWD aren't kept.
You can create a "fake" global variable by
creating a form (e.g. named frmGlobal)
make sure the form is always open but hidden
create a TextBox for each global variable you want (e.g. tVar1)
in your code, reference as e.g. Form_frmGlobal.tVar1
The disadvantage is that an unbound text box may not give you a specific data type you want
The two ways around that are
in your code, explicitly convert the textbox to the data type when referencing the global variable
e.g Clng(Form_frmGlobal.tVar1)
another option is create a one-row table and bind your textboxes on your hidden form to the table, so your data types are enforced
A bonus of this method is you can use for persistent storage between sessions
Caveat: make sure this table is local to a single user only, in the front end database file (don't want to put it in the back end database because of multi-users over-writing each other). This assumes you are using front end + back end separated databases, with distribution of front end to each user's workstation.
I see nothing in that statement that tells me it's a global variable. You set global variables above ALL Subs/Functions and below an Options Compare statement in a module, by stating:
PUBLIC X as string
Any other variable is only good until the sub or function has completed.
Also, Global variables MUST be declared on a PROPER MODULE. You can't declare them on a form's module.

Error when trying to access a textbox on a User Control assigned to a public variable - vb.net

I created two user controls with different user interfaces. Depending on a selection the user makes, one of these interfaces will be used in my class. Since I don't know until after the user makes a selection, I cannot declare the user control ahead of time so I created a public variable to later assign the correct user control to.
The error occurs when I try to access a control (textbox) on the user control. However, if I declare the user control without assigning it to the public variable, then I don't get an error. Also, if I were to assign the user control to the public variable as its being declared then I don't get an error either. I really do need to be able to pick between the two user controls though. I don't know what to do. Am I missing something? I appreciate any help.
Public Class VesselData
Public RCAVesselData
Public AOLVesselData
Public Sub New()
If Main.UserSelectedModule = "Arrival on Location" Then
OperatorView = New AOLVesselData 'User Control 1
ElseIf Main.UserSelectedModule = "Running Conventional Anchors" Then
OperatorView = New RCAVesselData 'User Control 2
End If
OperatorView.txtDistanceToFairlead.text = "A" 'THROWS MissingMemberException - Public member 'txtDistanceToFairlead' on type 'AOLVesselData' not found.
Dim Test as New AOLVesselData
Test.txtDistanceToFairlead.text = "A" 'DOES NOT THROW EXCEPTION
End Sub
The problem is that you are accessing a member that doesn't exist. From the code you have posted, of the AOLVesselData and RCAVesselData classes, it looks like the RCAVesselData class does not have a txtDistanceToFairlead member.
If you have a common set of methods/properties you expect both user controls to expose, refactor them into an Interface and have both user controls implement that Interface. That will make it easy to use them interchangeably.
Try using Shared instead of Public when you declare OperatorView. And, like tcarvin said, you might want to turn "Explicit" on (project compile options) or use "Option Explicit".

Is it a good practice to use global constants, types and functions inside VBA classes?

I have started using VBA classes and I have always tried to write my code such that each class is "independent", that is, it has everything it needs--constants, functions, etc--inside. Lately, though, this approach has resulted in code duplication since, instead of calling public functions in different modules, I copied some code from the "outside world" (in the same project) into a class just to maintain its "self-sufficiency".
I am considering changing a few classes so that they will be able to access functions, constants, types, etc. from other modules just like any other module can, but something in me is telling me this might not be a good practice. Can somebody tell me that what the little voice is saying is wrong? Is there a better approach?
Thanks.
Updates:
My apologies for not providing details earlier. Here's a sample code:
'-------------------------------------
'Module 1
'-------------------------------------
Public Const INITIAL_VALUE As String = "Start"
Public Const FINAL_VALUE As String = "End"
'more constants ...
Public Type SheetLoc
SheetName As String
SheetRow As Long
SheetColumn As Long
End Type
'more types ...
'-------------------------------------
'Module 2
'-------------------------------------
Public Function GetLocation(key As String) As SheetLoc
Dim myLoc As SheetLoc
'some codes here...
'
With myLoc
.SheetName = someValue
.SheetColumn = anotherValue
.SheetRow = stillAnotherValue
End With
GetLocation = myLoc
End Function
'more module functions
'-------------------------------------
'Class Module
'-------------------------------------
'some codes...
Public Sub SaveResults()
Dim currLoc As SheetLoc '<==== using a type defined outside of the class
'more declarations ....
'some codes here ....
If currentValue = INITIAL_VALUE Then '<=== referring to external constant
currLoc = GetLocation(someKey) '<=== calling an external function
ElseIf currentValue = FINAL_VALUE Then '<=== referring to an external constant
currLoc = GetLocation(anotherKey)
Else
currLoc = GetLocation(defaultKey)
End If
'populate data ...
'save results ...
End Sub
Note the codes with "<====" in the comments; the class uses types, functions and constants defined outside of the class, and this is what makes me wonder if it's a good practice or if there's a better option. I guess I just don't fully get the encapsulation concept.
I never put public constants in a class module. All, and I mean all, of my public variables and constants are in a standard module called MGlobals. That has two benefits. First, you and I know both know where to find them - they're somewhat dangerous and need to be findable. Second, if that module ever gets more than a few lines, I know I'm being lazy and need to refactor.
It's a good practice to try to keep your class modules modular. But don't go nuts with it. Good programming will never be dropping a selection of modules into a project and having them just work. There is, and should be, integration to do on any project of significance.
This is just so wrong. Op asked my own question perfectly, and the answer is just so flat.
IME, the answer OP was looking for (back in 2012!), was that they should forward the needed values through the ClassName.Module(optional thing as var,). Then they can send in the specific values for the presumably repeatable variants of a request, and receive a new answer for a request that matches other requests on other machines and can be used in another project without changing the class. While it is true that integration requires change, it should never be on the class side. If you destroy the integrity of the class it becomes a module.
Outside INI files on the other hand...

When to use a Class in VBA?

When is it appropriate to use a class in Visual Basic for Applications (VBA)?
I'm assuming the accelerated development and reduction of introducing bugs is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion?
It depends on who's going to develop and maintain the code. Typical "Power User" macro writers hacking small ad-hoc apps may well be confused by using classes. But for serious development, the reasons to use classes are the same as in other languages. You have the same restrictions as VB6 - no inheritance - but you can have polymorphism by using interfaces.
A good use of classes is to represent entities, and collections of entities. For example, I often see VBA code that copies an Excel range into a two-dimensional array, then manipulates the two dimensional array with code like:
Total = 0
For i = 0 To NumRows-1
Total = Total + (OrderArray(i,1) * OrderArray(i,3))
Next i
It's more readable to copy the range into a collection of objects with appropriately-named properties, something like:
Total = 0
For Each objOrder in colOrders
Total = Total + objOrder.Quantity * objOrder.Price
Next i
Another example is to use classes to implement the RAII design pattern (google for it). For example, one thing I may need to do is to unprotect a worksheet, do some manipulations, then protect it again. Using a class ensures that the worksheet will always be protected again even if an error occurs in your code:
--- WorksheetProtector class module ---
Private m_objWorksheet As Worksheet
Private m_sPassword As String
Public Sub Unprotect(Worksheet As Worksheet, Password As String)
' Nothing to do if we didn't define a password for the worksheet
If Len(Password) = 0 Then Exit Sub
' If the worksheet is already unprotected, nothing to do
If Not Worksheet.ProtectContents Then Exit Sub
' Unprotect the worksheet
Worksheet.Unprotect Password
' Remember the worksheet and password so we can protect again
Set m_objWorksheet = Worksheet
m_sPassword = Password
End Sub
Public Sub Protect()
' Protects the worksheet with the same password used to unprotect it
If m_objWorksheet Is Nothing Then Exit Sub
If Len(m_sPassword) = 0 Then Exit Sub
' If the worksheet is already protected, nothing to do
If m_objWorksheet.ProtectContents Then Exit Sub
m_objWorksheet.Protect m_sPassword
Set m_objWorksheet = Nothing
m_sPassword = ""
End Sub
Private Sub Class_Terminate()
' Reprotect the worksheet when this object goes out of scope
On Error Resume Next
Protect
End Sub
You can then use this to simplify your code:
Public Sub DoSomething()
Dim objWorksheetProtector as WorksheetProtector
Set objWorksheetProtector = New WorksheetProtector
objWorksheetProtector.Unprotect myWorksheet, myPassword
... manipulate myWorksheet - may raise an error
End Sub
When this Sub exits, objWorksheetProtector goes out of scope, and the worksheet is protected again.
I think the criteria is the same as other languages
If you need to tie together several pieces of data and some methods and also specifically handle what happens when the object is created/terminated, classes are ideal
say if you have a few procedures which fire when you open a form and one of them is taking a long time, you might decide you want to time each stage......
You could create a stopwatch class with methods for the obvious functions for starting and stopping, you could then add a function to retrieve the time so far and report it in a text file, using an argument representing the name of the process being timed. You could write logic to log only the slowest performances for investigation.
You could then add a progress bar object with methods to open and close it and to display the names of the current action, along with times in ms and probable time remaining based on previous stored reports etc
Another example might be if you dont like Access's user group rubbish, you can create your own User class with methods for loging in and out and features for group-level user access control/auditing/logging certain actions/tracking errors etc
Of course you could do this using a set of unrelated methods and lots of variable passing, but to have it all encapsulated in a class just seems better to me.
You do sooner or later come near to the limits of VBA, but its quite a powerful language and if your company ties you to it you can actually get some good, complex solutions out of it.
Classes are extremely useful when dealing with the more complex API functions, and particularly when they require a data structure.
For example, the GetOpenFileName() and GetSaveFileName() functions take an OPENFILENAME stucture with many members. you might not need to take advantage of all of them but they are there and should be initialized.
I like to wrap the structure (UDT) and the API function declarations into a CfileDialog class. The Class_Initialize event sets up the default values of the structure's members, so that when I use the class, I only need to set the members I want to change (through Property procedures). Flag constants are implemented as an Enum. So, for example, to choose a spreadsheet to open, my code might look like this:
Dim strFileName As String
Dim dlgXLS As New CFileDialog
With dlgXLS
.Title = "Choose a Spreadsheet"
.Filter = "Excel (*.xls)|*.xls|All Files (*.*)|*.*"
.Flags = ofnFileMustExist OR ofnExplorer
If OpenFileDialog() Then
strFileName = .FileName
End If
End With
Set dlgXLS = Nothing
The class sets the default directory to My Documents, though if I wanted to I could change it with the InitDir property.
This is just one example of how a class can be hugely beneficial in a VBA application.
I use classes if I want to create an self-encapsulated package of code that I will use across many VBA projects that come across for various clients.
I wouldn't say there's a specific criterion, but I've never really found a useful place to use Classes in VBA code. In my mind it's so tied to the existing models around the Office apps that adding additional abstraction outside of that object model just confuses things.
That's not to say one couldn't find a useful place for a class in VBA, or do perfectly useful things using a class, just that I've never found them useful in that environment.
For data recursion (a.k.a. BOM handling), a custom class is critically helpful and I think sometimes indispensable. You can make a recursive function without a class module, but a lot of data issues can't be addressed effectively.
(I don't know why people aren't out peddling BOM library-sets for VBA. Maybe the XML tools have made a difference.)
Multiple form instances is the common application of a class (many automation problems are otherwise unsolvable), I assume the question is about custom classes.
I use classes when I need to do something and a class will do it best:) For instance if you need to respond to (or intercept) events, then you need a class. Some people hate UDTs (user defined types) but I like them, so I use them if I want plain-english self-documenting code. Pharmacy.NCPDP being a lot easier to read then strPhrmNum :) But a UDT is limited, so say I want to be able to set Pharmacy.NCPDP and have all the other properties populate. And I also want make it so you can't accidentally alter the data. Then I need a class, because you don't have readonly properties in a UDT, etc.
Another consideration is just simple readability. If you are doing complex data structures, it's often beneficial to know you just need to call Company.Owner.Phone.AreaCode then trying to keep track of where everything is structured. Especially for people who have to maintain that codebase 2 years after you left:)
My own two cents is "Code With Purpose". Don't use a class without a reason. But if you have a reason then do it:)
You can also reuse VBA code without using actual classes. For example, if you have a called, VBACode. You can access any function or sub in any module with the following syntax:
VBCode.mysub(param1, param2)
If you create a reference to a template/doc (as you would a dll), you can reference code from other projects in the same way.
Developing software, even with Microsoft Access, using Object Oriented Programming is generally a good practice. It will allow for scalability in the future by allowing objects to be loosely coupled, along with a number of advantages. This basically means that the objects in your system will be less dependent on each other, so refactoring becomes a lot easier. You can achieve this is Access using Class Modules. The downside is that you cannot perform Class Inheritance or Polymorphism in VBA. In the end, there's no hard and fast rule about using classes, just best practices. But keep in mind that as your application grows, the easier it is to maintain using classes.
As there is a lot code overhead in using classes in VBA I think a class has to provide more benefit than in other languages:
So this are things to consider before using a class instead of functions:
There is no class-inheritance in vba. So prepare to copy some code when you do similar small things in different classes. This happens especially when you want to work with interfaces and want to implement one interfaces in different classes.
There are no built in constructors in vba-classes. In my case I create a extra function like below to simulate this. But of curse, this is overhead too and can be ignored by the one how uses the class. Plus: As its not possible to use different functions with the same name but different parameters, you have to use different names for your "constructor"-functions. Also the functions lead to an extra debug-step which can be quite annoying.
Public Function MyClass(ByVal someInit As Boolean) As MyClassClass
Set MyClass = New MyClassClass
Call MyClass.Init(someInit)
End Function
The development environment does not provide a "goto definition" for class-names. This can be quite annoying, especially when using classes with interfaces, because you always have to use the module-explorer to jump to the class code.
object-variables are used different to other variable-types in different places. So you have to use a extra "Set" to assign a object
Set varName = new ClassName
if you want to use properties with objects this is done by a different setter. You have to use "set" instead of "let"
If you implement an interface in vba the function-name is named "InterfaceName_functionName" and defined as private. So you can use the interface function only when you cast the Variable to the Interface. If you want to use the function with the original class, you have to create an extra "public" function which only calls the interface function (see below). This creates an extra debug-step too.
'content of class-module: MyClass
implements IMyInterface
private sub IMyInterface_SomeFunction()
'This can only be called if you got an object of type "IMyInterface"
end function
private sub IMyInterface_SomeFunction()
'You need this to call the function when having an object of the type "MyClass"
Call IMyInterface_SomeFunction()
end function
This means:
I !dont! use classes when they would contain no member-variables.
I am aware of the overhead and dont use classes as the default to do things. Usually functions-only is the default way to do things in VBA.
Examples of classes I created which I found to be useful:
Collection-Classes: e.g. StringCollection, LongCollection which provide the collection functionality vba is missing
DbInserter-Class: Class to create insert-statements
Examples of classes I created which I dont found to be useful:
Converter-class: A class which would have provided the functionality for converting variables to other types (e.g. StringToLong, VariantToString)
StringTool-class: A class which would have provided some functionality for strings. e.g. StartsWith
You can define a sql wrapper class in access that is more convenient than the recordsets and querydefs. For example if you want to update a table based on a criteria in another related table, you cannot use joins. You could built a vba recorset and querydef to do that however i find it easier with a class. Also, your application can have some concept that need more that 2 tables, it might be better imo to use classes for that. E.g. You application track incidents. Incident have several attributes that will hold in several tables {users and their contacts or profiles, incident description; status tracking; Checklists to help the support officer to reply tonthe incident; Reply ...} . To keep track of all the queries and relationships involved, oop can be helpful. It is a relief to be able to do Incident.Update(xxx) instead of all the coding ...
In VBA, I prefer classes to modules when:
(frequent case) I want multiple simultaneous instances (objects) of a common structure (class) each with own independent properties.
Example:Dim EdgeTabGoogle as new Selenium.EdgeDriverDim EdgeTabBing as new
Selenium.EdgeDriver'Open both, then do something and read data to and from both, then close both
(sometimes) I want to take advantage of the Class_Initialize and Class_Terminate automatic functions
(sometimes) I want hierarchical tree of procedures (for just variables a chain of "Type" is sufficient), for better readability and Intellisense
(rarely) I want public variables or procedures to not show in Intellisense globally (unless preceded by the object name)
I don't see why the criteria for VBA would be any different from another language, particularly if you are referring to VB.NET.