Reputation: 1516
Just a quick question on VBA
I am learning class modules in VBA and i have met a new practice of declaring variables inside class modules. Here it goes:
Public WithEvents TxtGroup As MSForms.TextBox
also
Dim Word1 As Word.Application
Dim bottomLabel As New System.Windows.Forms.Label
Here after the the As and the New keywords instead of seeing a data type or an object or a reference to a class object we see two words joined by a period just like some sort of directory... e.g. MSForms.TextBox since my question is a bit of out-of-the-box i couldn't locate on my VBA books an ample explanation for this transition in the declaration technique. I need to learn classes really fast and i would definitely like to ask why do i meet this practice since i have never seen it in a module.
I have seen examples as
Private Sub xlApp_NewWorkbook(ByVal Wb As Workbook)
Dim wks As Worksheet
With Wb
For Each wks In .Worksheets
wks.PageSetup.LeftFooter = “Created by: “ & .Application.UserName
wks.PageSetup.RightFooter = Now
Next wks
End With
End Sub
Why these code blocks have no namespaces in their declarations while others have? thanks for watching my question
Upvotes: 2
Views: 228
Reputation: 7830
Have a look at this MSDN article about Namespaces in VB.
In conjunction with programming the term namespace means means package:
A namespace is a container for a set of identifiers (also known as symbols, names).[1][2] Namespaces provide a level of indirection to specific identifiers, thus making it possible to distinguish between identifiers with the same exact name.
So a namespace enables classes with the same name to co-exist and be used side-by-side. In every package one or more classes with a unique name can reside. For example:
For example:
namespace Teachers
class Person end class
end namespace
namespace Doctors
class Person end class
end namespace
In order to create a politician object you need to uniquely identify the class, so you can't just write:
Dim p as Person
because the compiler can't know which from the two Person classes to instantiate. That is why you identify the class with it's namespace:
Dim t as Teachers.Person
Dim d as Doctors.Person
In the example given by you:
Dim Word1 As Word.Application
Word is the namespace, Application the class and thus the type of the variable!
When defining a variable, the last part (after the last dot) is always a class, everything before the last dot is a namespace! In the example given by you, you are using the TextBox from the Namespace Systems.Windows.Forms.
If the class name is unique and even if it resides in any namespace, there is no need to write it, because the compiler can infer the correct name automatically. In VB.NET there is the import keyword, with which you can import a namespace to your code in order to use the classes without qualifiying them with the namespace.
Upvotes: 3