- Social Media
- Smart Devices

Tutorial for Visual Basic Commands
By Leon Williams
Visual Basic, like any other programming language, employs special keywords known as commands. Unlike variables, which are named and defined within your code, command names are defined by the Visual Basic language itself and cannot be changed.
What Are Visual Basic Commands?
The difference between a variable and a command in programming is similar to the difference between a noun and a verb in the English language. A variable holds data, but a command evaluates or manipulates that data.
Differences in the names and use of different commands are essentially what make one programming language different from another. As a programmer, you may be able to accomplish the same task coding in either C++ or Visual Basic, but the code involved would be drastically different between the two projects because of the way each language defines and interprets commands.
In Visual Basic programming, the most basic commands---ones that you will use over and over in your projects---can be put into three categories: declarations, operators/math, and loops.
Essential Visual Basic Commands by Category
DECLARATIONS
Programming languages use commands called "declarations" to define and populate variables. Declarations can be a stumbling point for Visual Basic beginners because much of the syntax used is unique to Visual Basic.
"Dim" (and "As") is used to declare a variable. Examples: "dim MyString as string" or "n = dim n as integer."
"Static" is similar to what might be called a "global" in other languages; a "static" variable does not lose its assigned value until the entire program has been terminated. (I.e., it does not lose its value every time the particular procedure is ended.)
"Public" defines a variable that can be used externally (i.e., by procedures other than the one in which it is created).
OPERATORS AND MATH
Basic math functionality falls under the "operators" category. Mathematical symbols such as "+", "-", "/" and "*" serve their usual purpose. Comparative operators such as "and" and "or" are also used the same as you'd see them in other languages. Other Visual Basic commands categorized as operators:
"Eqv" performs a comparison against two logical variables. The command "Output = YesNoA eqv YesNoB" will set the variable Output "true" if both YesNoA and YesNoB are true.
"Like" compares a string against a pattern. The command "Output = MyString like MyPattern" will return a "true" value to Output if MyString adheres to the pattern defined by MyPattern.
The basic use of loops and conditional arguments in Visual Basic programming is largely identical to other modern programming languages. The familiar "if/then/else," "while" and "for each/next" arguments are all available for use in Visual Basic programming.
"Wend" is used as an "end" command for a "while" loop in Visual Basic. Programmers familiar with languages where a "while" loop uses "end," or languages limited to closing a "while" loop using parenthetical-type containers, will want to take note of the "wend" command.
Other Visual Basic Commands
These three categories are by no means an exhaustive reference for Visual Basic commands. There are hundreds more. One benefit of Visual Basic is the prevalence of predefined commands for advanced mathematical concepts and operating system interaction. Many processes that you would have to create "by hand" in other languages are available in Visual Basic as pre-existing commands, especially when it comes to things such as parsing and comparing files, or creating and manipulating Windows elements.
- MSDN Visual Basic Developer Center
Leon Williams has worked as a fiction editor, sporting goods retailer, rock musician, systems analyst, help desk technician and marketing coordinator. He holds a bachelor's degree from Northern Michigan University, where he studied English, computer science and new media. He has had work published in a variety of online venues as well as the Uncle John's Bathroom Reader series of books.
- The A.V. Club
- The Takeout
- The Inventory
Visual thinking
Designer Jason Santa Maria continues his excellent Under The Loupe series with a post about visual thinking. This one's got some great ideas to get your creative juices going.
Strong concepts don't always just come to us; sometimes they take work. Perhaps not real physical labor, but a process of bypassing the obvious ideas to get to the hidden ones. Some people call this "Creative Thinking", but when I was first introduced to this concept, it was presented to me as "Visual Thinking". I tend to prefer "Visual" as opposed to "Creative" as it helps to shift the focus back to design specifically. Let's define "Visual Thinking" as: A process of idea-finding and formulation, typically with simple tools like a pencil and paper, where the cumulation of ideas influences the whole.
Under The Loupe: #5 Visual Thinking [Jason Santa Maria]
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Objects and classes in Visual Basic
- 12 minutes to read
- 13 contributors
An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application, like a control or a form. An entire application can also be an object.
When you create an application in Visual Basic, you constantly work with objects. You can use objects provided by Visual Basic, such as controls, forms, and data access objects. You can also use objects from other applications within your Visual Basic application. You can even create your own objects and define additional properties and methods for them. Objects act like prefabricated building blocks for programs — they let you write a piece of code once and reuse it over and over.
This topic discusses objects in detail.
Objects and classes
Each object in Visual Basic is defined by a class . A class describes the variables, properties, procedures, and events of an object. Objects are instances of classes; you can create as many objects as you need once you have defined a class.
To understand the relationship between an object and its class, think of cookie cutters and cookies. The cookie cutter is the class. It defines the characteristics of each cookie, for example size and shape. The class is used to create objects. The objects are the cookies.
You must create an object before you can access its members, except for Shared members which can be accessed without an object of the class.
Create an object from a class
Determine from which class you want to create an object, or define your own class. For example:
Write a Dim Statement to create a variable to which you can assign a class instance. The variable should be of the type of the desired class.
Add the New Operator keyword to initialize the variable to a new instance of the class.
You can now access the members of the class through the object variable.
Whenever possible, you should declare the variable to be of the class type you intend to assign to it. This is called early binding . If you don't know the class type at compile time, you can invoke late binding by declaring the variable to be of the Object Data Type . However, late binding can make performance slower and limit access to the run-time object's members. For more information, see Object Variable Declaration .
Multiple instances
Objects newly created from a class are often identical to each other. Once they exist as individual objects, however, their variables and properties can be changed independently of the other instances. For example, if you add three check boxes to a form, each check box object is an instance of the CheckBox class. The individual CheckBox objects share a common set of characteristics and capabilities (properties, variables, procedures, and events) defined by the class. However, each has its own name, can be separately enabled and disabled, and can be placed in a different location on the form.
Object members
An object is an element of an application, representing an instance of a class. Fields, properties, methods, and events are the building blocks of objects and constitute their members .
Member Access
You access a member of an object by specifying, in order, the name of the object variable, a period ( . ), and the name of the member. The following example sets the Text property of a Label object.
IntelliSense listing of members
IntelliSense lists members of a class when you invoke its List Members option, for example when you type a period ( . ) as a member-access operator. If you type the period following the name of a variable declared as an instance of that class, IntelliSense lists all the instance members and none of the shared members. If you type the period following the class name itself, IntelliSense lists all the shared members and none of the instance members. For more information, see Using IntelliSense .
Fields and properties
Fields and properties represent information stored in an object. You retrieve and set their values with assignment statements the same way you retrieve and set local variables in a procedure. The following example retrieves the Width property and sets the ForeColor property of a Label object.
Note that a field is also called a member variable .
Use property procedures when:
You need to control when and how a value is set or retrieved.
The property has a well-defined set of values that need to be validated.
Setting the value causes some perceptible change in the object's state, such as an IsVisible property.
Setting the property causes changes to other internal variables or to the values of other properties.
A set of steps must be performed before the property can be set or retrieved.
Use fields when:
The value is of a self-validating type. For example, an error or automatic data conversion occurs if a value other than True or False is assigned to a Boolean variable.
Any value in the range supported by the data type is valid. This is true of many properties of type Single or Double .
The property is a String data type, and there is no constraint on the size or value of the string.
For more information, see Property Procedures .
Always keep the non-constant fields private. When you want to make it public, use a property instead.
A method is an action that an object can perform. For example, Add is a method of the ComboBox object that adds a new entry to a combo box.
The following example demonstrates the Start method of a Timer object.
Note that a method is simply a procedure that is exposed by an object.
For more information, see Procedures .
An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. Events can occur as a result of a user action or program code, or they can be caused by the system. Code that signals an event is said to raise the event, and code that responds to it is said to handle it.
You can also develop your own custom events to be raised by your objects and handled by other objects. For more information, see Events .
Instance members and shared members
When you create an object from a class, the result is an instance of that class. Members that are not declared with the Shared keyword are instance members , which belong strictly to that particular instance. An instance member in one instance is independent of the same member in another instance of the same class. An instance member variable, for example, can have different values in different instances.
Members declared with the Shared keyword are shared members , which belong to the class as a whole and not to any particular instance. A shared member exists only once, no matter how many instances of its class you create, or even if you create no instances. A shared member variable, for example, has only one value, which is available to all code that can access the class.
Accessing non-shared members
Make sure the object has been created from its class and assigned to an object variable.
In the statement that accesses the member, follow the object variable name with the member-access operator ( . ) and then the member name.
Accessing shared members
Follow the class name with the member-access operator ( . ) and then the member name. You should always access a Shared member of the object directly through the class name.
If you have already created an object from the class, you can alternatively access a Shared member through the object's variable.
Differences between classes and modules
The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces. If a class is marked with the MustInherit modifier, it can't be instantiated directly. However, it's still different from a module as it can be inherited while modules can't be inherited.
When the Shared modifier is applied to a class member, it is associated with the class itself instead of a particular instance of the class. The member is accessed directly by using the class name, the same way module members are accessed.
Classes and modules also use different scopes for their members. Members defined within a class are scoped within a specific instance of the class and exist only for the lifetime of the object. To access class members from outside a class, you must use fully qualified names in the format of Object . Member .
On the other hand, members declared within a module are publicly accessible by default, and can be accessed by any code that can access the module. This means that variables in a standard module are effectively global variables because they are visible from anywhere in your project, and they exist for the life of the program.
Reusing classes and objects
Objects let you declare variables and procedures once and then reuse them whenever needed. For example, if you want to add a spelling checker to an application you could define all the variables and support functions to provide spell-checking functionality. If you create your spelling checker as a class, you can then reuse it in other applications by adding a reference to the compiled assembly. Better yet, you may be able to save yourself some work by using a spelling checker class that someone else has already developed.
.NET provides many examples of components that are available for use. The following example uses the TimeZone class in the System namespace. TimeZone provides members that allow you to retrieve information about the time zone of the current computer system.
In the preceding example, the first Dim Statement declares an object variable of type TimeZone and assigns to it a TimeZone object returned by the CurrentTimeZone property.
Relationships among objects
Objects can be related to each other in several ways. The principal kinds of relationship are hierarchical and containment .
Hierarchical relationship
When classes are derived from more fundamental classes, they are said to have a hierarchical relationship . Class hierarchies are useful when describing items that are a subtype of a more general class.
In the following example, suppose you want to define a special kind of Button that acts like a normal Button but also exposes a method that reverses the foreground and background colors.
Define a class that is derived from an already existing class
Use a Class Statement to define a class from which to create the object you need.
Be sure an End Class statement follows the last line of code in your class. By default, the integrated development environment (IDE) automatically generates an End Class when you enter a Class statement.
Follow the Class statement immediately with an Inherits Statement . Specify the class from which your new class derives.
Your new class inherits all the members defined by the base class.
Add the code for the additional members your derived class exposes. For example, you might add a ReverseColors method, and your derived class might look as follows:
If you create an object from the ReversibleButton class, it can access all the members of the Button class, as well as the ReverseColors method and any other new members you define in ReversibleButton .
Derived classes inherit members from the class they are based on, allowing you to add complexity as you progress in a class hierarchy. For more information, see Inheritance Basics .
Compile the code
Be sure the compiler can access the class from which you intend to derive your new class. This might mean fully qualifying its name, as in the preceding example, or identifying its namespace in an Imports Statement (.NET Namespace and Type) . If the class is in a different project, you might need to add a reference to that project. For more information, see Managing references in a project .
Containment relationship
Another way that objects can be related is a containment relationship . Container objects logically encapsulate other objects. For example, the OperatingSystem object logically contains a Version object, which it returns through its Version property. Note that the container object does not physically contain any other object.
Collections
One particular type of object containment is represented by collections . Collections are groups of similar objects that can be enumerated. Visual Basic supports a specific syntax in the For Each...Next Statement that allows you to iterate through the items of a collection. Additionally, collections often allow you to use an Item[] to retrieve elements by their index or by associating them with a unique string. Collections can be easier to use than arrays because they allow you to add or remove items without using indexes. Because of their ease of use, collections are often used to store forms and controls.
Related topics
Walkthrough: Defining Classes Provides a step-by-step description of how to create a class.
Overloaded Properties and Methods Overloaded Properties and Methods
Inheritance Basics Covers inheritance modifiers, overriding methods and properties, MyClass, and MyBase.
Object Lifetime: How Objects Are Created and Destroyed Discusses creating and disposing of class instances.
Anonymous Types Describes how to create and use anonymous types, which allow you to create objects without writing a class definition for the data type.
Object Initializers: Named and Anonymous Types Discusses object initializers, which are used to create instances of named and anonymous types by using a single expression.
How to: Infer Property Names and Types in Anonymous Type Declarations Explains how to infer property names and types in anonymous type declarations. Provides examples of successful and unsuccessful inference.
Submit and view feedback for

Additional resources

- VB.NET-Forum
- Tips 'n Tricks
- Einstieg in .NET
- VB 5/6-Forum
- API-Katalog
- Komponenten
- LEGO Mindstorms
- Web-Entwicklung
- App-Entwicklung
- Forenarchive
- Projekte & Tools
- Fachbegriffe
- Dateiformate
- Tipp-Upload
- Ausschreibungen
- Wettbewerbe
- Registrieren
- Community-Forum
- ActiveVB e.V.
- Vereinsforum
- Treffen und Workshops
- Kontakt und Impressum
Startseite / Tutorials / Einfache Klassen
Einfache Klassen
von sebastian klose, übersicht , was sind klassen .
Der Oberbegriff für Klasse ist das Objekt. Aber was ist ein Objekt? Visual Basic Programme bestehen fast ausschließlich aus Objekten, so ist beispielsweise jedes Steuerelement (Commandbutton, Textbox, Formular, etc.) ein Objekt. Um dieses theoretische Gebilde des Objekts zu verstehen, verlassen wir kurz Visual Basic und verwenden zum besseren Verständnis ein reales Objekt: Die (Schul-) Klassen.
Wir stellen und vor, es gäbe keinerlei Schulsysteme. Die Eltern aller Kinder unterrichteten diese selber. Das Chaos wäre perfekt, denn keines der Kinder würde gezielt unterrichtet. Jedes Kind hätte einen anderen Wissensstand. Es gäbe keine Zertifikate, die eine bestimmte Bildungsstufe nachweisen, usw. Irgendwann würde jemand versuchen, dieses Chaos zu beseitigen. Er schafft zunächst nur theoretisch ein Gedankengebäude - ein Konzept - in dem Kinder gemäß ihres Alters in Klassen zusammengefasst werden. Diese Klassen haben z.B. die Eigenschaft nur Kinder eines bestimmten Alters aufzunehmen. Gleichzeitig werden die Kinder dieser Klassen durch bestimmte Lehrer und damit durch unterschiedliche Methoden unterrichtet. Natürlich gibt es nicht nur eine Klasse, sondern mehrere, die sich durch verschiedene Eigenschaften und die Anwendung verschiedener Methoden von einander unterscheiden.
Kommen wir nun aber zurück zu Visual Basic: Dort finden wir, wenn wir die Werkzeugsammlung betrachten, eine Reihe von Symbolen, hinter denen sich in dem Moment, in dem wir die Werkzeugsammlung betrachten, nichts weiter als ein theoretisches Gebäude mit Vorschriften verbirgt. Diese Vorschriften definieren, was geschehen soll, wenn eines dieser Konzepte in der Praxis umgesetzt wird. Auch in der objektorientierten Programmierung sprechen wir bei einem solchen theoretischen "Gebäude" (siehe Schule) von einer Klasse.
Es gibt Verfahren - nennen wir es passend zum dem Beispiel mit der Schule "Einschulung" - das aus der Theorie Praxis werden lässt. Unsere theoretische Klasse wird zu einem mehr oder weniger greifbaren Objekt. Bei der Programmierung heißt dieser Vorgang natürlich nicht Einschulung, sondern Instanzierung. Wenn man also das Symbol eines Commandbuttons von der Werkzeugsammlung auf einem Formular platziert, wird die Klasse CommandButton instanziert und man erhält ein CommandButton-Objekt. Dieses Objekt kann, wie die jetzt eingeschulte Klasse, durch bestimmte Eigenschaften klassifiziert werden. Sie bestimmen also beispielsweise die MaximaleStundenProTag-Eigenschaft (Schulklasse) bzw. die Caption-Eigenschaft (CommandButton).
Das Konzept einer Klasse gibt es nur ein einziges Mal. Auch die Rahmenbedingungen, in denen sich eine Klasse bewegen kann, werden nur ein einziges Mal vorgeschrieben. Sämtliche Aufgaben einer Klasse werden nur ein einziges Mal bestimmt. Aber dennoch lässt sich eine Klasse beliebig oft zu einem realen Objekt instanzieren, und mehrere Instanzen einer Klasse (Objekte) können völlig unabhängig von einander agieren.
Beim Programmieren werden die Konzepte und Regeln (die Rahmenbedingungen) einerseits von bestimmten Variablen definiert, andererseits durch Programmcode. Wenn wir eine Klasse instanzieren, schafft Visual Basic ein Objekt vom Typ dieser Klasse. Das Objekt enthält den Code der zuvor durch die Klasse definiert wurde. Der Code wiederum bestimmt, was geschieht, wenn man eine bestimmte Methode auf das Objekt anwendet oder eine Eigenschaft des Objekts verändert.
In VB-Code könnte ein derartiges Objektmodell einer Schule in etwa so dargestellt werden:
Listing 1: Achtung: dieser Code kann nicht ausgeführt werden!
Die erste Klasse
Nun wollen wir die erste Klasse in Visual Basic realisieren. Dazu erstellen wir zunächst ein neues Projekt vom Typ "Standard EXE" und fügen diesem mit einem Klick auf den Menüpunkt Klassenmodul hinzufügen im Menü Projekt eine neue Klasse hinzu.
Im nun erscheinenden Dialogfeld wählen wir "Klassenmodul" aus und geben unsere Klasse im Eigenschaftsfenster noch einen Namen, z.B. "TestKlasse". Als nächstes müssen wir die oben genannten "Rahmenbedingungen" für die Klasse schaffen. Dazu fügen wir der Klasse eine Eigenschaft hinzu (der Name der Eigenschaft soll einfach "Eigenschaft" sein). Im Klassenmodul sollte nun folgender Code enthalten sein:
Listing 2: Quelltext einer Eigenschaft
Nun möchten wir aber, dass unsere Eigenschaft einen Standardwert bekommen kann, also fügen wir noch eine Funktion (welche in Klassen übrigens Methoden genannt werden) hinzu:
Listing 3: Quelltext einer Methode
Jetzt müssen wir noch den Code für das Formular schreiben. Zunächst platzieren wir auf dem Formular aber 3 CommandButtons und eine TextBox. Das ganze sollte dann in etwa so aussehen:
Der Quellcode sollte nun folgender sein (natürlich ohne die Zeilennummern!):
Zunächst wird hier in Zeile 3 ein Objekt aus der grade definierten Klasse erstellt. Das Schüsselwort New sorgt dafür, dass unser Objekt auch wirklich instanziert wird, und somit verwendet werden kann. In Zeile 8 sind schon die Parallelen zu den Objekten aus der Werkzeugsammlung (Commandbuttons etc.) ersichtlich. Alle Methoden und Eigenschaften einer Klasse werden (genau wie bei den Controls aus der Werkzeugsammlung) durch den Namen des Objektes + Punkt + Name der Eigenschaft/Methode angesprochen.
Was nun noch etwas störend ist an diesem Beispiel, ist dass unsere Eigenschaft nicht zu Beginn ihren Standardwert hat und dieser erst durch einen Aufruf der Methode SetzeStandard() hergestellt wird. Um dieses Problem zu lösen besitzen alle Objekte 2 vordefinierte Methoden, nämlich den Konstruktor und den Destruktor. Der Konstruktor wird ausgeführt sobald eine Instanz der Klasse geschaffen wurde (also in Zeile 3). Der Destruktor wird beim Beenden des Programms ausgeführt, in ihm könnte beispielsweise belegter Arbeitsspeicher der Klasse wieder freigegeben werden. Wir benötigen allerdings zunächst nur den Konstruktor. Wir können ihn der Klasse ganz einfach hinzufügen, indem wir ihr die Methode Class_Initialize() implementieren:
Listing 5: Konstruktor Beispiel
Und siehe da, wenn wir die Anwendung nun starten und auf "Anzeigen" klicken, wird tatsächlich der Standardwert ausgegeben.
Als letztes wollen wir der Klasse noch ein Ereignis hinzufügen. Jedes Mal, wenn die Eigenschaft den Standardwert bekommt, soll das Ereignis "StandardGesetzt" ausgelöst werden. Dazu ändern wir zunächst den Code der Klasse wie folgt ab:
Listing 6: Ereignis Beispiel
Zu den Änderungen:
- In Zeile 3 teilen wir Visual Basic mit, dass diese Klasse ein Event (=Ereignis) auslösen soll, diesen wird mit der RaiseEvent - Funktion in Zeile 18 getan
- Der Standardwert unserer Eigenschaft wurde in einer Konstanten abgelegt
Jetzt muss der Code des Formulars nur noch ein wenig abgewandelt werden, damit uns das Ereignis der Klasse dort zur Verfügung steht:
- Das Schlüsselwort, um an die Ereignisse eines Objektes heranzukommen, lautet in VB WithEvents (siehe Zeile 3)
- Das Erstellen des eigentlichen Objektes wurde in die Form_Load() - Funktion verlagert, da VB ein gleichzeitiges WithEvents und New nicht unterstützt
- In Zeile 30 wird dann das Event definiert, wie man es auch von CommandButtons, TextBoxes, etc kennt.
Polymorphismus in Visual Basic
Mit Polymorphismus meint man die Eigenschaft, Objekte aus anderen Objekten zu erstellen, auch Vererbung genannt. Dies wird von Visual Basic leider erst ab .NET richtig unterstützt. Die einzige Möglichkeit der Vererbung in VB 6 sind die sogenannten Interfaces. Dieses sind abstrakte Klassen, d. h. Klassen, die nur die Funktionsrümpfe enthalten. Diese Interfaces können dann von beliebigen Klassen implementiert werden. Dadurch "erbt" die Klasse alle Funktionen des Interfaces. Dies hat den Vorteil, dass sich alle Klassentypen die ein bestimmtes Interface implementiert haben, untereinander zuweisen lassen. Hier ein Beispiel dazu:
Als ersten wollen wir unser Interface definieren, dazu fügen wir einem neuen Projekt eine Klasse hinzu, die wir "ITier" nennen (das "I" steht dabei für Interface). Sie soll folgenden Code enthalten:
Listing 8: Eine abstrakte Klasse
Da man aus solchen abstrakten Klassen keine Objekte erstellen kann, brauchen wir noch weitere Klassen, die dieses Interface implementieren. Deswegen fügen wir als nächstes die Klasse "Hund" hinzu. Sie enthält folgenden Code:
- In der zweiten Zeile wird durch das Schlüsselwort Implements unser Interface eingebunden. Alle im Interface definierten Funktionsrümpfe müssen von der Hund-Klasse mit Code gefüllt, oder zumindest als leere Funktionen implementiert werden.
- Durch die neue Methode Beiss() wird der Hund spezialisiert. Er ist zwar immer noch ein Tier (weil er dieses Interface implementiert), aber er hat im Vergleich zu einem normalen Tier weitere Eigenschaften.
Da es wenig Sinn hat Interfaces zu nutzen, wenn es nur eine Klasse gibt, die dieses implementiert, definieren wir noch eine zweite, und zwar die Klasse "Katze":
Die Katze unterscheidet sich vom Hund in sofern, dass sie nicht beißen kann, dafür kann sie aber kratzen. Trotzdem bleibt sie, genau wie der Hund, aber ein Tier, weil sie ebenfalls das Interface implementiert.
Jetzt müssen wir nur noch den Code unseres Formulars aufsetzten. Zunächst bekommt unser Formular 4 CommandButtons (Captions: Essen; Schlafen; Beißen; Kratzen). Dazu kommen noch zwei OptionButtons mit den Aufschriften Hund + Katze. Das ganze sieht dann in etwa so aus:
Der Code sollte so aussehen:
Zunächst definieren wir die Variable Tier vom Typ ITier. Da dies ein Interface ist und aus diesem kein Objekt erstellt werden kann, fällt das Wort New hier weg. Stattdessen wird im Form_Load() - Ereignis ein neuer Hund instanziert. Dies ist nur dadurch möglich, dass der Hund das Interface ITier implementiert hat.
Mit den beiden OptionButtons kann man zwischen einem Hund und einer Katze wählen. Mit einem Klick auf "Essen" oder "Schlafen" wird die entsprechende Funktion aus dem Interface aufgerufen, da diese dort nur deklariert, jedoch nicht definiert ist, wird es an die Klasse, die das Interface implementiert hat weitergeleitet. Also entweder an den Hund oder die Katze, je nachdem als was das Tier momentan definiert ist.
Bei einem Klick auf "Beißen" wird zunächst kontrolliert, ob das Tier ein Hund oder eine Katze ist. Dies geschieht mit der VB-Funktion TypeOf. Wenn es wirklich ein Hund ist, wird unser Tier in eine spezialisierte Klasse vom Typ Hund übertragen, es bleibt jedoch die selbe Klasse, es wird dabei keine neue Klasseninstanz erstellt. Das ist nötig, da das Objekt Tier vom Typ ITier ist und die Methode Beiss() nicht kennt. Der Hund kennt diese aber, da sie in ihm definiert wurde. Der selbe Vorgang wird dann auch mit der Katze wiederholt.
Zusammenfassung
Dies war ein einfacher Einstieg in die Welt der Klassen(module). Für Fragen steht Ihnen der Autor gerne zur Verfügung. Im Anhang finden Sie zwei Beispiele und dieses Tutorial als Worddokument.
Tutorial und Beispielprojekte als Download [102000 Bytes]
Ihre Meinung
Falls Sie Fragen zu diesem Tutorial haben oder Ihre Erfahrung mit anderen Nutzern austauschen möchten, dann teilen Sie uns diese bitte in einem der unten vorhandenen Themen oder über einen neuen Beitrag mit. Hierzu können sie einfach einen Beitrag in einem zum Thema passenden Forum anlegen, welcher automatisch mit dieser Seite verknüpft wird.
Erstellt: 01.01.2002 Aktualisiert: 30.12.2011 Redaktion: Philipp Burch
Copyright © 1998–2023 ActiveVB. Alle Rechte vorbehalten. Impressum | Datenschutz | Fehler melden

AutoMacro: Ultimate VBA Add-in

Read all reviews
Return to VBA Code Examples
VBA Class Module Tutorial & Examples
In this Article
Class Modules vs. Modules
Advantages of using class modules, disadvantages of using class modules, inserting a class module, creating an object item, creating a collection, using your new object, summary of creating an object using a class module, using a class module to create a variable repository, turning your object into an add-in.
This tutorial will teach you about Class Modules in VBA. You’ll learn what they are and how to use them.
VBA Class Modules – Introduction
When you insert modules into the Visual Basic Editor (VBE) in order to enter your code, you may have noticed that you can also insert what is called a ‘Class Module’.

The class modules work in a very different way to the ordinary modules in that they facilitate creating a Component Object Model (COM) which can then be used within your normal VBA code
Effectively, you create an object which works in the same way as a built in Excel object such as ‘Worksheets’. In the Worksheets Object , you have a number of properties and methods which allow you to get the number of worksheets within a workbook or each individual name of a worksheet, or numerous other information
When you create a new Object in this way, you are creating a building block which can be used anywhere within VBA. The Object has a number of properties and methods that can be accessed by your VBA code from anywhere within the workbook without having to keep re-writing the code over again.
As well as referring to your new object from a standard VBA module, you can also use it in the code behind a UserForm that is part of your custom application
You can also use it where you have placed Active X controls onto a worksheet, such as a command button or a drop down. These controls all use VBA, and your new object can easily be incorporated into the event code for these controls.
You can also turn your object into an Excel add-in. Your object will automatically be available to other users who have that add-in loaded. This adds your own multi-tier architecture to your Excel application
Excel is a multi-tiered application. There is the client services layer, which drives the actual worksheet window that that the user is familiar with. The Excel object model is the next layer underneath. Press F2 in a VBA module and you will be able to see the huge number of objects and members of those objects that are the engine of Excel. Note that your new object will also be displayed here.
Finally, underneath all of this, you have the data services layer which holds all the data that you have entered into the worksheets and cells. Excel accesses this using the Excel Object model.

Creating a Class Module allows you to extend the Excel Object Module with your own custom objects and members
This article explains to you how you to create a simple hierarchy of objects using Class Modules.
- You can develop a robust building block which can be used in any number of different Excel applications
- Once it is thoroughly tested, then is can be relied on to always produce the correct results in the same way as the built-in Excel objects
- If updates are made to code elsewhere in the application, the new object will still continue to work in the same way
- You can use your new object in other Excel applications as an add-in
- The objects can be re-used in other applications and helps in debugging
- They can be difficult to create and understand.
- Naming conventions are very important because this is what you will see when use your object within a normal module.
- If you have not created a class module before, they can be difficult to understand and there is a steep learning curve
- Impossible to make changes at run-time – you have to re-set the project.
- If Properties and Private Variables have the same name then infinite loops can occur resulting in errors
Select Insert | Class Module from the VBE (Visual Basic Editor) menu. The new Class Module will automatically be called ‘Class 1’, but this needs to be changed immediately to the name that you are going to use for your object

You change the name in the Properties window where the arrow is pointing. You simply type in your new name, and this will change in the Class Modules collection
If the Properties window is not visible, then select View | Properties on the VBE menu or press F4
Call your new class module ‘MyItem’ and double click the name in the tree-view in the Project Explorer to display the code window for it.
This example will create a top-level object called ‘MyItems’ with a member object below it called ‘MyItem’ which will hold the individual data for each item. Once created it will work in the same way as a built in Excel Object. For example, there is an object called ‘Worksheets’ which is a collection of each worksheet within your workbook. There is also an object called ‘Sheet’ which represents each individual worksheet within your workbook, and holds all the properties and methods for each worksheet. This object relates to the ‘Worksheets’ collection object.
You can iterate through the ‘Worksheets’ collection, viewing each ‘Sheet’ in turn. In the same way you will be able to iterate through the ‘MyItems’ collection viewing the properties that you created in the ‘Myitem’ member.
The first thing to do is to create the sub object for the member level which will hold the actual items within the collection of the top-level object. This is the equivalent of the members (e.g. name, visible, count) within the ‘Sheet’ object in Excel. This code is entered into the class module called ‘MyItem’
Class modules have Properties and Methods. Properties are effectively like variables, in that they hold values of data like variables, and Methods are like sub routines or functions.
In the sub object we are going to create two properties for the object – Item and Detail
Initially two string variables need to be declared to hold the values for the properties:
These need to be declared in the Declarations section at the top of the code for the class module so that they can be used in all sub routines throughout the module
They need to be given unique names to make them different from the properties that we are going to create, so an ‘m’ (for member) has been put in front of each name.
The variables are declared as Private so they cannot be seen by anyone using the object. They are working variables for use within the object code and are not there as part of the final object.
The next step is to set up code to give access to the two properties. You do this by means of a Property Let and a Property Get statement for each property. These must be Public otherwise the top-level object will not have any visible properties
This code creates the means to read and write values to the two properties (Item and Detail) using the two private variables that were defined in the declarations section of the module.
The ‘vdata’ parameter is used to pass data to the property concerned.
It is important that each property has a ‘Let’ and ‘Get’ statement and that the property name is the same in each case. You could end up with two different properties if miss-spelt – one that you can read from and one that you can write to!
To help with creating this code, you can use Insert | Procedure on the VBE menu to create a code skeleton which will create the initial code for the ‘Get’ and ‘Let’ properties for a given property name
This will display a pop-up window where you type the property name in and select ‘Property’ on the radio buttons:

Click ‘OK’ and the skeleton code will be added into the class module:
This prevents any mistakes over names of properties. You simply add your code in between the ‘Public Property’ and ‘End Property’ statements.
You now have an object called ‘MyItem’ which will hold all the data for this exercise.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

The next stage is to create a top-level object as a Collection object to give access to the properties that you have set up in the ‘MyItem’ object
Again, you need to define a working object to act as the collection object in the same way that you defined the two string variables in the ‘MyItem’ object.
Again, this this has to have a unique name which is why there is an ‘m’ (member object) in front of the name, and it is also declared as ‘Private’ so that it does not appear when the new object is being used
Next, you need to populate the Class_Initialize code. This runs when you first use the object within your code, and it determines what values will be loaded into the object
You can access this sub routine by selecting ‘Class’ in the first drop down and ‘Initialize’ in the second drop down of the module window
The code sets up an object called ‘objItem’ using the definition of ‘MyItem’ which we built as a class module earlier on.
It then creates a new Collection based on the ‘mItems’ object defined earlier
It iterates through values held on Sheet1 of the workbook and puts them into the properties that we created for the ‘MyItem’ object. Note that when you use ‘objitem’, a drop down appears showing the two properties, exactly as if you were using a built-in Excel object.
The item object is then added into the collection object which now holds all the data in the property values.
The input data does not have to be taken from a worksheet. It could be static values, or it could come from a connection to a database such as Microsoft Access or SQL Server, or it could come from another worksheet.
You then need to add a public function called ‘Item’
This allows you to refer to individual objects within the collection object by their index number. This function provides a ‘mirror’ of what is going on in the ‘mMyItems’ collection in the background.
You will also need to add a property called ‘Count’ so that your code can establish how many ‘MyItem’ objects are in the ‘MyItems’ collection, should you wish to iterate through it.
In this case you only need a ‘Get’ property because it is read-only. It uses the mItems collection because this already has a count property built into it.
You now have an object (MyItems) with a full hierarchy defined by the object ‘MyItem’
To make the whole thing work, you now need to populate a worksheet (Sheet1) with data so that the Class Initialize routine can collect this into the object
Your spreadsheet should look like this:

You can now use your Collection object (MyItems) within a standard Excel VBA module. Enter the following code:
This code creates an object called ‘MyClass’ based on the collection object that you created called ‘MyItems’. This fire off the ‘Initialize’ routine that extracts all the data from the worksheet into the object.
It displays the number of items in the collection and then iterates through the collection showing the ‘Item’ text and the ‘Detail’ text. You will notice that when you refer to the ‘MyClass’ object in your code, you will see a list of the two member properties which helps in adding the correct property.
If you change the value of a cell in the input data on the spreadsheet, this will automatically be updated in the collection when you run the above code again, since when you dimension the object, the initialize routine runs and picks up all the new data
If you use the word ‘Static’ instead of ‘Dim’ the initialise routine does not run and the old values are kept, so long as the code is continuously running. If the data on the spreadsheet changes this will not be reflected in the object
As you have seen, creating a hierarchy of class modules to use as an object is quite a complicated business, even for a structure as simple as the example provided here. The scope for making mistakes is enormous!
However, it does have huge advantages in making your code more elegant and easier to read. It is also easier to share with other Excel applications and developers by turning it into an Add-In.
In this example of how to create an object to hold data, it would be a normal approach to create a multi-dimensional array to hold the multi-column spreadsheet data, and you would write a line of code to update or read each element in the array. This would probably end up being quite messy, and mistakes could easily be made in addressing the various elements.
With your new object, you can simply refer to it and the members that you have created below it to hold the data.
Also, if the data changes in the spreadsheet (or in a linked database if you have used this as a data source within your class module) whenever you use the ‘Dim’ statement the initialize routine will be called and the data will be instantly updated. No need to write code to re-populate your array.
VBA Programming | Code Generator does work for you!
When you write VBA code you use variables all over the place, all with different scopes. Some may only be defined for a particular procedure, some for a particular module, and some may be global variables that can be used all over the application
You can create a class module that will hold a large number of variables, and because it is an object, it can be used anywhere within your code, even on a user form or in an Active X control that you have placed on a worksheet.
The added advantage is that when you refer to your variable object, you will see a list of all the variable names held in the object sorted into ascending order.
To create a repository, you need to insert a new class module. You do this by using Insert | Class Module from the VB Editor menu
Change the name to ‘MyVariables’ using the same methodology as previously discussed in this article.
Enter the following code:
This code sets up ‘Let’ and ‘Get’ properties for two variables (‘Variable1’ and ‘Variable2’). The Let and Get properties are required for each of your variables so that they are read / write
You can use your own names for the variables instead of the sample ones in this code, and you can add further variables, making sure that each new variable has a ‘Let’ and ‘Get’ statement.
The private declaration of the variable ‘mV’ is to create a working variable that is only used within the class module to transfer values.
To use the variable repository, enter the following code into a standard module:
This code creates a global instance of your ‘MyVariables’ object that you created. You only need to do this declaration once from anywhere within your code.
The code first displays the value of ‘Variable1’ to show that it is empty.
A value of 10 is assigned to ‘Variable1’ and the new value within the object is then displayed to show that this property now holds this value.
Because the instance of the ‘MyVariables’ object has been defined globally, you can refer to any of the defined variables within the object from anywhere within your code.
This has a huge advantage in that if you want to use your variables anywhere in your code, you only need to define one global variable, and from that instance, all the variables can be freely accessed and modified throughout your code.
So far, the code for the object creation is within your workbook application. However, if you want to be able to share your object with other developers or in other Excel applications of your own, you can turn it into an Add-In
To do this, all that needs to happen is to save the file as an Add-In. Select File | Save As and a browser window will appear
Select the file type as Add-In (.xlam) from the file type drop down and click OK. The file will be saved to the Add-In folder by default, but you can change the location.
You can then incorporate the add-in file into your Excel applications, giving you the flexibility to make use of your new object

To include your new Add-In into Excel, click on File on the Excel ribbon, and then click on Options at the bottom of the left-hand pane
Click on ‘Add-Ins’ in the left-hand pane in the pop-up window that appears. At the bottom of the window is a button marked ‘Go’
Click on this and an ‘Add-In’ pop-up window will appear. Click on ‘Browse’ and then locate your Add-In file. You will then be able to refer to your object in your code.

VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
(No installation required!)
Free Download

AutoMacro: VBA Add-in with Hundreds of Ready-To-Use VBA Code Examples & much more!
What is automacro.
AutoMacro is an add-in for VBA that installs directly into the Visual Basic Editor. It comes loaded with code generators, an extensive code library, the ability to create your own code library, and many other time-saving tools and utilities that add much needed functionality to the outdated VBA Editor.
Ultimate VBA Add-in
Offer expires soon!
Sale Ends Friday at Midnight
VBA (Macros) Code Examples Add-in

Es gibt die verschiedensten Arten von Objekten: Autos, Häuser, Bäume usw. Jede Art von Objekt lässt sich allgemein beschreiben. So hat z. B. eine Datei unter anderem eine bestimmte Größe und ein Änderungsdatum. Es muss nur ein einziges Mal definiert sein, dass so etwas zu einer Datei gehört, dann wissen wir: Jede beliebige Datei hat diese Eigenschaften.
Ebenso verhält es sich mit den Objekten in der Programmierung: Die Festlegung, welche Elemente zu einer bestimmten Art von Objekt gehört, erfolgt in einer Klasse . Von der Klasse können dann beliebig viele Objekte abgeleitet werden.
Nun kann man so viele Autos im Code einbauen, wie man möchte. Jedes ist ein eigenes Objekt mit allen Elementen aus Auto .
Allerdings haben so die beschriebenen Fahrzeuge nur einen Verweis auf die Objektdefinition Auto . Damit ist nur festgelegt, dass diese Variablen existieren und ausschließlich je ein Auto -Objekt enthalten können. Neue Objekte müssen darüber hinaus noch erzeugt werden:
Objektzuweisungen erfordern die Set -Anweisung, und New erstellt dann das eigentliche Objekt (eine neue Instanz der Klasse). Solange noch keine Objektzuweisung erfolgt ist, enthält eine Objektvariable den speziellen Wert Nothing . Objektdeklaration und -zuweisung kann auch in nur einem Schritt erfolgen:
Die Unterscheidung zwischen Objektdeklaration und -zuweisung wird vielleicht klarer, wenn man das obige Beispiel mit Dim Familienkutsche As Object wiederholt: Jetzt handelt es sich bei Familienkutsche um ein allgemeines Objekt, und erst eine Set -Anweisung bestimmt, um welche Art von Objekt es sich überhaupt handelt.
Visual Basic: Mit Klassen programmieren
Wenn Sie ein Abonnement des Magazins 'DATENBANKENTWICKLER' besitzen, können Sie sich anmelden und den kompletten Artikel lesen. Anderenfalls können Sie das Abonnement hier im Shop erwerben.
Wer bisher mit VBA oder C# gearbeitet hat und zu VB wechseln möchte, sieht sich bei der Entwicklung von WPF-Anwendungen einigen Änderungen gegenüber. Dieser Artikel liefert die Grundlagen zum Umgang mit Namespaces und zur Programmierung von Klassen. Zum Experimentieren mit den Beispielen nutzen wir das Tool LINQPad 5.
Im Gegensatz zu C# werden Klassen unter Visual Basic nicht durch eine geschweifte Klammer eingeleitet und beendet, sondern wir arbeiten mit dem für Visual Basis typischen Start- und Endzeilen:
Class -Elemente können dabei mit folgenden Modifizierern ausgestattet werden:
- Public : Die Klasse ist innerhalb der Assembly und auch von anderen Assemblies aus sichtbar.
- Friend : Die Klasse ist nur innerhalb der Assembly sichtbar, zu der sie gehört. Dies ist der Standard-Modifizierer, wenn Sie dem Schlüsselwort Class weder Public noch Friend oder einen anderen Modifizierer voranstellen!
Klasse erstellen
Eine Klasse wird typischerweise in einer eigenen Code-Datei angelegt. Wenn Sie ein neues WPF-Fenster anlegen, fügt Visual Studio beispielsweise eine eigene Datei mit der Dateiendung .xaml.vb hinzu, welche als Code behind-Modul für das WPF-Fenster dient. Wenn Sie eine neue Klasse benötigen, die nicht als Code behind-Modul für ein WPF-Element dient, erledigen Sie dies normalerweise über den Dialog Neues Element hinzufügen... , den Sie am einfachsten durch Markieren des Projekts im Projektmappen-Explorer und anschließendes Betätigen der Tastenkombination Strg + Umschalt + A aufrufen.
Hier wählen Sie dann den Eintrag Klasse aus und geben den gewünschten Namen an, in diesem Fall Beispiel (siehe Bild 1).

Die neue Klasse wird dann mit dem Public -Schlüsselwort ausgezeichnet. Wenn Sie nicht wollen, dass die Klasse in anderen Assemblies genutzt werden kann, ändern Sie Public also in Friend :
Objekte auf Basis von Klassen initialisieren
Es gibt verschiedene Arten, eine Klasse zu initialisieren. Wenn Sie den Zeitpunkt der Deklaration und der Initialisierung trennen möchten, nutzen Sie zwei Anweisungen:
Anderenfalls haben Sie die Wahl zwischen den folgenden beiden Schreibweisen. Die erste kennen Sie von VBA:
Die zweite ist eine Kombination aus dem Zweizeiler:
Weitere Klassen anlegen
Wenn Sie weitere Klassen anlegen wollen, haben Sie die Wahl: Sie können jeweils eine neue Datei mit jeder Klasse erstellen, was wie oben beschrieben funktioniert. Theoretisch können Sie aber auch mehrere Klassen in einer Datei speichern. Sie können neue Klassen auch innerhalb bestehender Klassen anlegen. Das sieht dann etwa wie folgt aus:
Mit Klassen experimentieren
Die schönste Benutzeroberfläche auch zum Experimentieren mit Klassen ist das Tool LINQPad . Damit können Sie, was für die Beispiele dieses Artikels sinnvoll ist, unter Language den Eintrag VB Program auswählen. Es wird dann automatisch eine Sub Main eingerichtet, unterhalb derer Sie die Klassen dieses Artikels definieren können. In Sub Main greifen Sie dann ganz einfach auf die Klassen zu (siehe Bild 2). Wenn Sie auf die Start -Schaltfläche klicken, wird Sub Main ausgeführt. Wir fügen der untergeordneten Klasse einfach eine öffentliche Eigenschaft hinzu:

Die untergeordnete Klasse können Sie etwa wie folgt deklarieren und initialisieren:
Für solche untergeordneten Klassen gibt es neben den Modifizierern Public und Friend noch drei weitere mögliche Modifizierer. Diese Modifizierer gelten natürlich auch für die anderen Elemente einer Klasse, also beispielsweise Methoden, Eigenschaften oder Ereignisse:
- Private : Die Klassen, Methoden, Ereignisse und Eigenschaften können nur innerhalb des Objekts genutzt werden, in der diese auch definiert wurde. Außerhalb der übergeordneten Klasse ist sie nicht sichtbar. Wenn Sie die Klasse UntergeordneteKlasse von oben als Private deklarieren würden, könnten Sie nicht von der Methode Public Main darauf zugreifen.
- Protected : Die Klasse, Methoden, Ereignisse und Eigenschaften können nur innerhalb des Objekts genutzt werden, indem diese definiert wurden, und in Objekten auf Basis von Klassen, die von der ursprünglichen Klasse abgeleitet sind. Ableitungen von Klassen stellen wir später noch vor.
- Protected Friend : Die Klasse, Methoden, Ereignisse und Eigenschaften können nur innerhalb des Objekts und der Assembly genutzt werden, indem diese definiert wurden, und in Objekten auf Basis von Klassen, die von der ursprünglichen Klasse abgeleitet sind.
Felder von Klassen
Sie können einer Klasse sogenannte Felder hinzufügen, indem Sie direkt unterhalb der Class -Ebene Variablen deklarieren. Dies können Variablen mit dem Modifizierer Public , Private oder einem der anderen Modifizierer sein. Public -Felder können Sie auch von außerhalb lesen und schreiben. Die Klasse im folgenden Beispiel hat eine öffentliche und eine private Variable. Die öffentliche ist von außen per IntelliSense verfügbar und kann sowohl geschrieben als auch abgefragt werden:
Felder als nur lesbar markieren
Wenn ein Feld nur lesenden, aber keinen schreibenden Zugriff ermöglichen soll, deklarieren Sie es mit dem Schlüsselwort ReadOnly :
Diese liefert dann beim Zugriff von außen den Wert null zurück. Schreibend können Sie von außen nicht auf dieses Feld zugreifen, und von innerhalb der Klasse, in der es definiert ist, auch nur sehr eingeschränkt. Sie können es in der Deklarationszeile mit dem gewünschten Wert initialisieren:
Die Konstruktor-Methode
Die einzige weitere Alternative bei schreibgeschützten Feldern ist die Verwendung der Konstruktor-Methode. Also schauen wir uns diese gleich hier an. Die Konstruktor-Methode ist wie unter C# die Methode, die beim Initialisieren eines Objekts auf Basis der Klasse automatisch ausgeführt wird.
Unter C# heißt diese wie die Klasse selbst, unter Visual Basic ist dies ganz anders: Hier lautet der Name der Konstruktor-Methode schlicht New . Die Konstruktor-Methode der folgenden Klasse KlasseMitFeld weist dem Feld ZeichenketteNurLesbar eine Zeichenkette zu. Die Methode Sub Main initialisiert die Klasse und gibt dann als Beweis die zugewiesene Zeichenkette aus:
Die Konstruktor-Methode ist ein von vielen VBA-Entwicklern schmerzlich vermisstes Feature: Damit können Sie einer Klasse direkt beim Initialisieren wichtige Informationen übermitteln, die dann auch direkt verarbeitet werden können – beispielsweise, um einer Kunde -Klasse direkt den Namen und die Adresse des Kunden zu übermitteln.
Eigenschaften
Felder können fast wie Eigenschaften genutzt werden – es gibt schreib- und lesbar Felder oder auch nur lesbare Felder ( ReadOnly ). Eigenschaften erlauben aber eine genauere Steuerung der Berechtigungen und erlauben auch noch das Ausführen weiterer Aktionen, wenn der Eigenschaftswert geschrieben oder gelesen wird. Eine Eigenschaft enthält in der Regel eine lokale Variable, die den Eigenschaftswert speichert (die sogenannte Member-Variable), sowie ein öffentliches Property -Konstrukt, welches jeweils einen sogenannten Getter und einen Setter enthält. Das sieht dann insgesamt wie folgt aus:
Dies war die Leseprobe dieses Artikels. Melden Sie sich an, um auf den vollständigen Artikel zuzugreifen.
Die mit einem * markierten Felder sind Pflichtfelder.
Diese Website verwendet Cookies, um Ihnen die bestmögliche Funktionalität bieten zu können. Wenn Sie damit nicht einverstanden sein sollten, stehen Ihnen folgende Funktionen nicht zur Verfügung:
- Artikel in den Warenkorb legen
- Artikelempfehlungen und vieles mehr

[HOW TO] Eigene Klassen erstellen, verwalten und verwenden
In Ihrem Webbrowser ist JavaScript deaktiviert. Um alle Funktionen dieser Webseite nutzen zu können, muss JavaScript aktiviert sein.
7. Januar 2011, 03:13
VB.NET-Quellcode
- Dim MeinEis As Eis
- Enum s_Eissorte
- Schokolade = 1
- Vanille = 2
- Erdbeer = 3
- Private m_Eissorte As s_Eissorte = s_Eissorte.Schokolade 'Hier "speichern" wir nun die Auswahl der Enum in einer Variable
- Public Class Eis
- Private m_Eissorte As s_Eissorte
- Private m_Kugeln As Integer
- Private m_Becher As Boolean
- Private m_Name As String
- Public Property Name As String 'Unsere Eigenschaft ist öffentlich, da sie auch zugänglich sein soll. Und sie ist nicht ReadOnly, also auch änderbar
- Get 'Die Get-Klausel gibt den angegebenen Wert zurück, hier "m_Name".
- Return m_Name
- Set ( ByVal value As String ) 'Die Set-Klausel gibt es bei ReadOnly-Propertys nicht, da Set einen Wert ändert.
- m_Name = value
- End Property
- Public Sub New ( ByVal p_Eissorte As s_Eissorte, ByVal p_Kugeln As Integer , ByVal p_Becher As Boolean , ByVal p_Name As String )
- m_Eissorte = p_Eissorte
- m_Kugeln = p_Kugeln
- m_Becher = p_Becher
- m_Name = p_Name
- Dim MeinEis As Eis = New Eis(s_Eissorte.Vanille, 2 , True , "Vanilla At Dinner" ) 'Ein bisschen kitschig ;)
- Dim MeineKuehltruhe As New List( Of Eis)
- MeineKuehltruhe.Add( New Eis(Eis.s_Eissorte.Vanille, 2 , True , "Vanilla For Dinner" ))
- MeineList.Items.Clear() 'Erst alle EInträge löschen
- For Each EinzelEis As Eis In MeineKuehltruhe 'Für jedes Eis in unserer Liste...
- With MeineList
- .Items.Add(EinzelEis.Eissorte.ToString) 'Spalte 1: Eissorte
- .Items.Item(.Items.Count - 1 ).SubItems.Add(EinzelEis.Kugeln) 'Spalte 2: Anzahl der Kugeln
- .Items.Item(.Items.Count - 1 ).SubItems.Add(EinzelEis.Becher) 'Spalte 3: Becher?
- .Items.Item(.Items.Count - 1 ).SubItems.Add(EinzelEis.Name) 'Spalte 4: Name des Eises
Eisdiele.rar
Dieser Beitrag wurde bereits 2 mal editiert, zuletzt von „ X-Zat “ ( 7. Januar 2011, 14:48 )
Ähnliche Themen
Umsetzung von Haushaltsbuch

Wie mache ich eine Funktion wo ich die Eigenschaften eines Objekts ändere?
Texte Analysieren
Auf variable anderer klasse zugreifen
Class in form öffnen
Eingabe als Variablenname
1 Benutzer hat hier geschrieben


IMAGES
VIDEO
COMMENTS
One of the greatest advantages of Visual Basic is that its structure is simple, especially the executable code. It is also an integrated development environment (IDE) with easy-to-use tools and utilities that allows for rapid development of...
Visual Basic, like any other programming language, employs special keywords known as commands. Unlike variables, which are named and defined within your code, command names are defined by the Visual Basic language itself and cannot be chang...
Designer Jason Santa Maria continues his excellent Under The Loupe series with a post about visual thinking. This one's got some great ideas to get your creative juices going. Designer Jason Santa Maria continues his excellent Under The Lou...
To define a class · Create a project by clicking New Project on the File menu. · Select Windows Application from the list of Visual Basic project
Each object in Visual Basic is defined by a class. A class describes the variables, properties, procedures, and events of an object.
In diesem Video lernen Sie, was Objekte und Klassen genau sind und wie Sie diese anwenden. Dabei legen Sie eine eigene Klasse an und fügen
VB.NET Tutorial 12 - Klassen (1) WICHTIG [E-Learning] (Programmieren lernen).
C# zum Gruseln | Oliver Sturm · C++ Grundlagen Tutorial #023 Klassen und Objekte · Visual Basic (VB.NET) – Full Course for Beginners · ChatGPT
In this tutorial show you how to use classes in Visual Basic using Visual Studio. I describe the difference between a class and an object.
In diesem Tutorial soll erklärt werden, wie man mit Visual Basic einfache Klassen erstellen und verwenden kann. Dieser Lehrgang soll nur
When you insert modules into the Visual Basic Editor (VBE) in order to enter your code, you may have noticed that you can also insert what is called a 'Class
Ebenso verhält es sich mit den Objekten in der Programmierung: Die Festlegung, welche Elemente zu einer bestimmten Art von Objekt gehört, erfolgt in einer
Eine Klasse wird typischerweise in einer eigenen Code-Datei angelegt. Wenn Sie ein neues WPF-Fenster anlegen, fügt Visual Studio beispielsweise
Hallo Community! Besonders für die Anfänger in VB.Net dürfte die Verwendung von Klassen interessant sein, da sich ohne Klassen schnell