Создание пользовательских типов данных в VBA Excel. Оператор Type, его описание и параметры. Создание массива «одномерных массивов» с пользовательскими данными.
Определение пользовательских типов данных
Пользовательский тип данных в VBA Excel представляет из себя набор элементов, каждому из которых пользователем присваивается свой тип данных. Другими словами, пользовательский тип данных — это набор данных разного типа, который может быть присвоен одной переменной.
Если простую переменную (не массив) объявить с пользовательским типом данных, она будет представлять из себя «одномерный массив»* с элементами разных типов данных, определенных пользователем.
Если с пользовательским типом данных объявить переменную массива, она будет представлять из себя массив «одномерных массивов»* пользовательских данных.
* Выражение «одномерный массив» взято в кавычки, так как фактически это не массив, а набор пользовательских данных, но для практического применения это не имеет значения.
Синтаксис оператора Type
Type <strong>Name</strong> <strong>Element</strong>_1 as <strong>Tip</strong> <strong>Element</strong>_2 as <strong>Tip</strong> <strong>Element</strong>_3 as <strong>Tip</strong> ———————— <strong>Element</strong>_n as <strong>Tip</strong> End Type |
Пользовательский тип данных в VBA Excel может быть объявлен с ключевым словом Public или Private, которое явно укажет зону его видимости. Если ключевое слово опущено, конструкция с оператором Type по умолчанию объявляется с зоной видимости Public.
Параметры оператора Type
Параметр | Описание |
---|---|
Name | Имя пользовательского типа данных, по которому этот тип данных будет присваиваться переменным. |
Element | Наименование отдельного элемента пользовательского типа данных. |
Tip | Тип данных отдельного элемента (стандартный тип VBA). |
Применение пользовательских типов данных
Применение пользовательских типов данных в VBA Excel рассмотрим на примере домиков для животных.
Объявление пользовательского типа данных
Объявление пользовательского типа данных (конструкция с оператором Type) размещается в самом начале модуля в разделе Declarations.
Пример 1
Type Domik naimenovaniye As String obyem_m3 As Single material As String kolichestvo As Long End Type |
В этом примере:
- Domik — имя, по которому этот тип данных будет присваиваться переменным;
- naimenovaniye — наименование домика для животных;
- obyem_m3 — объем домика в куб. метрах;
- material — материал, из которого сделан домик;
- kolichestvo — количество домиков на складе.
Заполнение данными массива
Обычно в качестве контейнеров для пользовательских типов данных в VBA Excel используются массивы. В простую переменную можно уместить только один набор пользовательских данных, а в массив — сколько нужно. В следующем примере мы заполним трехэлементный массив тремя наборами пользовательских данных.
Если представить набор пользовательских данных как «одномерный массив», то таким образом мы создадим массив «одномерных массивов» с пользовательскими данными.
Пример 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Sub Primer2() ‘Объявляем трехэлементный массив ‘с пользовательским типом данных Dim a(1 To 3) As Domik ‘Заполняем первый элемент массива a(1).naimenovaniye = «Скворечник» a(1).obyem_m3 = 0.02 a(1).material = «сосна» a(1).kolichestvo = 15 ‘Заполняем второй элемент массива a(2).naimenovaniye = «Собачья будка» a(2).obyem_m3 = 0.8 a(2).material = «береза» a(2).kolichestvo = 5 ‘Заполняем третий элемент массива a(3).naimenovaniye = «Клетка кролика» a(3).obyem_m3 = 0.4 a(3).material = «металл» a(3).kolichestvo = 6 End Sub |
Обращение к пользовательским данным в массиве
Для обращения в коде VBA Excel к пользовательским данным в массиве используется та же конструкция, что и при записи: указывается элемент массива и через точку наименование элемента пользовательских данных.
Пример 3
‘Считываем информацию из массива Dim b As Variant b = a(2).naimenovaniye MsgBox b b = a(3).obyem_m3 MsgBox b b = «Мы продаем следующие товары: « _ & a(1).naimenovaniye & «, « _ & a(2).naimenovaniye & » и « _ & a(3).naimenovaniye MsgBox b |
Для наглядной демонстрации вставьте строки кода Примера 3 перед строкой End Sub Примера 2.
When thinking about custom objects / types in VBA most users turn to the VBA Class and create additional modules that quickly start cluttering their VBA Projects. Often these turn out to be simply structures, for the sole purpose of grouping several variables within a single object, bereft of any procedures or functions. VBA does not allow you to create subfolders in your VBA Project, so next time consider creating a VBA Type instead!
Below an example VBA Type name Person as well as usage:
'Declaration of Person Type Type Person name as String surname as String age as Long End Type 'Example usage of created Type Sub TestType Dim p as Person p.name = "Tom" p.surname = "Hanks" p.age = 54 Debug.Print p.name & " " & p.surname & ", age " & p.age 'Result: Tom Hanks, age 54" End Sub
What is a VBA Type and why use it?
What is a VBA Type? The Type statement defines a new user-defined data type containing one or more variables (basic VBA data types, custom Types or objects including custom VBA Classes). VBA Types fill the gap between native basic VBA data types such as Strings, Integers, Booleans etc. and custom objects – VBA Classes. Type declarations can only consist of variables.
Why would you want to use a VBA Type? Why use a cannon to shoot a fly? i.e why create a new VBA Class when all you need to is to group several variables into a new data type. One other thing is that Types don’t need separate VBA Modules and are embedded into existing modules, saving you space and preventing VBA Module cluttering.
Syntax of the VBA Type
The VBA Typed can be defined within VBA Modules, at the beginning, similarly like global variables. The syntax of a VBA Type looks like:
Type TypeName VariableName [as VariableType] '... End Type
VBA Types can:
- Have object such as other VBA Types or VBA Classes as variables
- Contain arrays – both static (predefined size) and dynamic (dynamically sized/resized)
- Be declared within VBA Modules. Types can also be declared within Forms and Classes, however, have to be declared Private (scoped only to Form or Class)
VBA Types can’t:
- Contain procedures or functions
- Be declared as Public in Classes and Forms
VBA Types are treated like other types (not objects) hence does not require to be defined using the Set statement. A Type object can be immediately used after it has been declared.
Type SomeType num as Long '... End Type Sub TestType() Dim myType as SomeType Set myType = New SomeType 'WRONG! myType.num = 10 'OK! End Sub
VBA Type examples
Now that we now the basic let’s look at some VBA Type examples. The Type example below is an excellent example of how much you can “squeeze” into a custom VBA Types.
Type CustomType someString As String threeCharacterStrings As String * 3 someNumber As Long someEnum As CustomEnum someObject As Object predefinedSizeArray(10) As Long dynamicSizedArray() As Long End Type
Now let’s use this newly defined VBA Type:
Enum CustomEnum EnumValue1 EnumValue2 EnumValue3 End Enum Sub TestCustomType() Dim myType As CustomType myType.someString = "Hello there!" myType.threeCharacterStrings = "Hello!" 'Will be trimmed to "Hel" myType.someEnum = EnumValue1 myType.someNumber = 10 Set myType.someObject = CreateObject("Scripting.Dictionary") myType.predefinedSizeArray(0) = 20 ReDim myType.dynamicSizedArray(20) As Long myType.dynamicSizedArray(1) = 100 End Sub
The VBA Type can basically aggregate any VBA Type within – including objects, classes, enums etc.
Types are typically compared to VBA Classes. Similarly most VBA users start by creating a class instead of contemplating the use of a simple VBA Type. Let’s thus compare the 2.
Property | VBA Type | VBA Class |
---|---|---|
Contains variables |
|
|
Contains procedures / functions |
|
|
Need to be defined using the Set statement |
|
|
Can be declared in any module |
|
|
VBA Type vs Module
Consider the reasons for creating new objects. In general I encourage the creation of Types and Classes as this goes in line with Object-Oriented Programming, however sometimes this is an overkill.
Are you creating the new Type / Class to have an easily accessible list of variables? Why not use a VBA Module instead. Simply make sure you variables are Public.
VBA Modules are singletons – objects accessible within the whole project and which variables have a single instance. As you probably know Modules like Classes can have procedures and functions.
VBA Types on the other hand are a simple vehicle of grouping variables into a new data type. Hence, don’t use them as singletons.
Summary
Hopefully, now you will consider using VBA Types when pondering a reason for creating a new custom VBA structure. I encourage you to use VBA Types and VBA Classes more often as you will notice how your code becomes more readable, comprehensive and less redundant. Do read my post on writing shorter VBA code if you want to read more tips on VBA best practices.
In my last week’s Blog post I elaborated on data types and their use in VBA.
Beyond using the readily available native data types we’re all familiar with, such as Integer, Date, String and Boolean, we can define our own, user-defined data type.
What is a User-Defined Data Type?
Simply put, a user-defined data type is a group of variables of native data types.
Here’s an example of grouping together several variables to define a new data type representing (or holding) information about a vehicle:
Type Vehicle
VIN as Long
Make as String
Model as String
Year as Integer
End Type
That’s it! As simple as that.
We can now dimension variables of type Vehicle:
Dim vehLeasedCar as Vehicle
We now have a kind of a hierarchy: a variable of type Vehicle containing sub-variables of different (native) types: Long, String and Integer in this example.
We can think of the sub-variables as properties of the Vehicle-type variable and use the “dot” to address each of these sub-variables. Let’s assign some values to our vehLeasedCar variable:
vehLeasedCar.VIN = 4656418
vehLeasedCar.Make = “Ford”
vehLeasedCar.Model = “Taurus”
vehLeasedCar.Year = 2001
In the same way, we can read the values of our variable (or its sub-variables). Let’s print out our vehicle’s model:
Debug.Print vehLeasedCar.Model
Why use User-Defined Data Types?
I can think of two main reasons to make use of user-defined data types:
- They are suitable for records arrangement in a readable format
- They are very efficient to process, even more than collections
Think of a process that needs to store and manipulate 5,000 vehicles.
One way would be to have a two-dimensional array store a table-like structure of the vehicles. This is valid (and you know how much I love arrays), and even performant. However, it would not be that clear by viewing the code what we are doing. What do you find more telling in your code: arrCars(i,j) or arrCars(i).Model?
Let’s define another data type to store information about an employee:
Private Type TEmployeeRecord
Name As String
DOB As Date
Age As Integer
City As String
Score As Integer
End Type
Consider how readable and self-explanatory the following Sub is, tasked with printing out all data of an employee, passed over as a TEmployeeRecord type variable:
Sub PrintEmployeeReport(employee As TEmployeeRecord)
With employee
Debug.Print .Name, .City, .DOB, .Age, .Score
End With
End Sub
Storing Many Records in an Array
Of course, storing a single record, as in the above examples, is not very helpful. We typically need to store many records of data in our program.
For this, we can combine our own defined data type (record structure) with a one-dimensional array.
To illustrate this in an example, let’s pick up a list of employees with some data on them from an Excel table and arrange it in an array of employees’ records. Our table look like this:
We first use a 2-dimensional array as an interim structure to quickly read the table from the Worksheet:
Dim arrEmployees() As Variant
arrEmployees = ThisWorkbook.Worksheets("Scores").Range("ScoresTable[#Data]").Value
Next, we loop our array and transfer each employee (“row”) in the array into a new, 1-dimentional array, holding employees’ records:
Dim employees(5) As TEmployeeRecord
Dim i As Integer
For i = LBound(arrEmployees, 1) To UBound(arrEmployees, 1)
With employees(i - 1)
.Name = arrEmployees(i, 1)
.DOB = arrEmployees(i, 2)
.Age = arrEmployees(i, 3)
.City = arrEmployees(i, 4)
.Score = arrEmployees(i, 5)
End With
Next i
With that, we have an efficient array of employees to work with.
We can now write a function to return the score of an employee, given a pointer to the array of employees we prepared and the employee name to look for.
Function GetScoreOfEmployee(strName As String, employees() As TEmployeeRecord) As Integer
Dim i As Integer
GetScoreOfEmployee = 0
For i = LBound(employees) To UBound(employees)
With employees(i)
If (.Name = strName) Then
GetScoreOfEmployee = .Score
Exit For
End If
End With
Next i
End Function
See how elegant and clear this function is? We’re looping the employees array, checking each employee name to match strName we’re looking for, returning his score upon a successful match.
Here’s how we can make use of the above function to ask the user for a name of an employee and get his score (we’ll store his score in the intScore variable). We’re making use of the employees array we have populated earlier with our employees:
Dim strName As String
Dim intScore As Integer
strName = InputBox("Name of employee:", "Query Employee Form")
intScore = GetScoreOfEmployee(strName, employees)
If (intScore = 0) Then
MsgBox "Employee not found", vbOKOnly + vbInformation, "Employee Error"
Else
MsgBox strName & "'s score: " & intScore, vbOKOnly + vbInformation, "Employee Score Result"
End If
By the way, if you are not familiar with the InputBox function, I have a detailed Blog post about it for you here. Similarly, the MsgBox function is explained here.
Unfortunately, Excel VBA doesn’t allow us to add user-defined type variables to a collection, therefore we’re missing out on a potentially very useful and efficient data structure. One can argue that if a collection is our best structure to maintain our records, we can implement our records as objects defined in a Class Module instead of a user-defined data type. Yes, I have a series of Blog posts about objects and Class Modules starting right here.
The above examples are featured in my flagship on-line course: Computer Programming with Excel VBA, in case they seemed familiar to you 😉.
Hey, a small request from me to you: please share this Blog post so that we can help more colleagues with Excel VBA.
Let’s say you are trying to create a school management system. Here, you will have different types of variables like student name, student roll no, class, etc. A school also has teachers, so there will be teacher names, teacher subject, classes, etc. Similarly, there will be many other objects like, librarian, classes, principle etc. Now having different variables for each entity in school will be messy work. How about creating a data type of student, teacher, classes, etc that stores values related to them. For this we can use defined data types of VBA.
In this article, we will learn how you can create your own data type in VBA. They are referred to as UDTs of VBA.
Defining a User Defined Data Type
To define a structure or UDTs in VBA we use Type___End Type block. Here’s the syntax of a UDT.
Type Tname_Of_Data_Type var1 as datatype 'datatype can be anything, int, array,or even UDT var2 as datatype Var3() as datatype --- VarN() as datatype End Type
So to define a custom data type in VBA we start with Type Keyword. Then we write the name of our custom data type. It is convention to use T before the Name of Data Type so that you can differentiate between vba collections and UDTs.
The DataTypes can be anything. And Integer, String, Variant, another UDT, Arrays, collections, anything.
To use your UDT in the program declare its variable like any other variable.
Sub UseUDT 'Declaring variable of user defined data type Dim myVar1 as Tname_Of_Data_Type Dim myVar2 as Tname_Of_Data_Type End Sub
Simple. Now to use the variables within this UDT we use dot operator. Use the name of the data type followed by a dot and name of variable within.
Sub UseUDT 'Declaring variable of user defined data type Dim myVar1 as Tname_Of_Data_Type Dim myVar2 as Tname_Of_Data_Type myVar1.var1="Abcd" myVar2.Var2="xyvz" End Sub
Enough of the theory, let’s jump into an example to see how it works.
Create A Student Variable that Stores Information Related to Student
So we have a task to create a user defined data type that stores information related to students.
A student has a first name, last name, roll number, date of birth, class, section, subjects.
So let’s create it.
'Created a Public Student Data Type Public Type Tstudent fName As String 'For First Name lName As String 'For Last Name rNo As Integer 'For Roll Number clss As string 'For Class section As String 'For Section Name subjects() As String 'For Subjects of student End Type 'Use this Tstudent type in subroutine Sub StudentsInfo() 'Creating and initializing student type variable Dim student1 As Tstudent student1.fName = "Manish" student1.lName = "Singh" student1.rNo = 12334 student1.clss = 10 student1.section = "A" ReDim student1.subjects(2) student1.subjects(0) = "physics" student1.subjects(1) = "Math" 'Printing student details. Debug.Print (student1.fName) Debug.Print (student1.lName) Debug.Print (student1.rNo) Debug.Print (student1.clss) Debug.Print (student1.section) Debug.Print (student1.subjects(0)) Debug.Print (student1.subjects(1)) End Sub
When you run the above sub it will print the result as shown below:
Singh
12334
10
A
physics
Math
Creating an Array of UDTs and Accessing Elements
Similarly you can create as many as variables of Tstudent type you need. You can even create an array of Tstudent type like any other data type.
Public Type Tstudent fName As String 'For First Name lName As String 'For Last Name rNo As Integer 'For Roll Number clss As string 'For Class section As String 'For Section Name subjects() As String 'For Subjects of student End Type 'Creating an arrays of Tstudents type Sub SchoolInfo() Dim schoolName As String Dim students() As Tstudent schoolName = "Senior School" ReDim students(10) For i = 0 To 9 students(i).fName = "name" & Str(i + 1) students(i).rNo = i + 1 Next i Debug.Print ("Name : Roll No") For i = 0 To 9 Debug.Print (students(i).fName & " : " & students(i).rNo) Next i End Sub
When you run this code, this will be printed in the immediate window.
name 1 : 1
name 2 : 2
name 3 : 3
name 4 : 4
name 5 : 5
name 6 : 6
name 7 : 7
name 8 : 8
name 9 : 9
name 10 : 10
In the above code, first defined UDT structure before and the sub (I’ll explain later why). The we just created an array using a dim keyword like we do for any variable in VBA.
Then we used Redim to define the size of arrays. Afterwards we use a for loop to initialize the array.
To access the structure’s elements we use another for loop. That is it.
Why Did We Declare UDT on Top of the Module?
If we declare a UDT first in a module, outside of any subroutine or function, it is available to all the modules in the workbook. It means if you have a hundred subs and functions in a module all of them can declare Student type variables in their body.
If the UDT is not private, it will be available to all the modules in the workbook. If want a structure (UDT) to be available only to a containing module, declare it private.
Private Type Tstudent fName As String lName As String rNo As Integer clss As Integer section As String subjects() As String End Type
You can’t have UDT on a procedural level. It means you can’t define a user defined data type inside a subroutine or function.
Nested User Defined Types
Let’s say you have UDT called a car. Car has its own elements. Similarly you have a UDT called a bike that can have its own properties.
Now let’s say you need a data type called vehicle. Vehicle can have a car and bike as its elements. Can we do this? Yes we can do this. See the below code
Private Type Tcar seats As Integer ac As Boolean typ As String color As String manufacturer As String Dop As Date rc_no As String End Type Private Type Tbike seats As Integer typ As String color As String manufacturer As String Dop As Date rc_no As String End Type Private Type Tvehicle number_of_Vehicle As Integer bike As Tbike car As Tcar End Type Sub vehicleVarification() Dim myVehicles As Tvehicle myVehicles.number_of_Vehicle = 2 myVehicles.bike.seats = 1 myVehicles.bike.typ = "Racing" myVehicles.car.seats = "4" myVehicles.car.ac = True Debug.Print myVehicles.number_of_Vehicle Debug.Print myVehicles.bike.typ Debug.Print myVehicles.car.ac End Sub
Here, we have defined three user defined data type. First is Tcar that contains some information related to cars. Second is bike, it also contains some information about bike.
The third UDT is Tvehicle. It contains one variable to store number of vehicles and two variables of Tcar and Tbike type.
Private Type Tvehicle
number_of_Vehicle As Integer
bike As Tbike
car As Tcar
End Type
To access variables of Tcar and Tbike we can use Tvehicle data type. In the sub, we have defined only one variable of Tvehicle type as myVehicles. When we create this variable VBA creates variables of Tcar and Tbike too.
To initialize and access variables of Tcar and Tcar, we can use myVehicle variable. As you can see in the code.
myVehicles.number_of_Vehicle = 2
myVehicles.bike.seats = 1
myVehicles.bike.typ = «Racing»
myVehicles.car.seats = «4»
myVehicles.car.ac = True
When we run the sub, this how result occurs.
This feature really increases the power of programming VBA exponentially. You can structure your data type like real world entities. You can create relationships between data types which can be useful in a big project.
So yeah guys, this is how you can create and use a user defined data type or structure in VBA. I hope I was able to explain it. If you have any questions regarding this article or any other VBA related questions, ask me in the comments section below. I’ll be really happy to hear from you.
Related Articles:
VBA variables in Excel| VBA stands for Visual Basic for Applications. It is a programming language from Microsoft. It is used with Microsoft Office applications such as MSExcel, MS-Word and MS-Access whereas VBA variables are specific keywords.
Excel VBA Variable Scope| In all the programming languages, we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers.
ByRef and ByVal Arguments | When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in the original argument.
Delete sheets without confirmation prompts using VBA in Microsoft Excel | Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.
Add And Save New Workbook Using VBA In Microsoft Excel 2016| In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc
Display A Message On The Excel VBA Status Bar| The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering.
Turn Off Warning Messages Using VBA In Microsoft Excel 2016| This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.
Popular Articles:
50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.
The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets.
COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific values. Countif function is essential to prepare your dashboard.
How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.
19
В объектных моделях приложений Office наряду с массивами используются коллекции. Коллекции – это специальные объекты, которые предназначены для хранения наборов одинаковых элементов. Коллекции обычно удобнее, чем массивы; они изначально безразмерны и в них предусмотрен стандартный набор свойств и методов.
VBA позволяет создавать структурные, так называемые пользовательские типы данных, аналогичные записям языка Pascal или языков PL/1 и COBOL. Например, если нужно обрабатывать сведения о результатах экзаменационной сессии, то можно создать пользовательский тип данных с названием Успеваемость.
Type Успеваемость ФИО As String * 20
№_Зач_кн As String * 8 Дисциплина As String * 20 Оценка As String * 20
End Type
Примечание1
Пользовательский тип данных определяется вверху модуля, в процедуре которой он используется, перед началом введения кода процедуры.
Если пользовательский тип данных создан, то для объявления переменной этого типа следует применить инструкцию Dim.
Пример
Sub Пользоват_Тип()
Dim Студенты As Успеваемость Студенты.ФИО = InputBox(«Введите ФИО») Студенты.№_Зач_кн = InputBox(«№_Зач_кн») Студенты.Дисциплина = InputBox(«Дисциплина») Студенты.Оценка = InputBox(«Оценка»)
MsgBox Студенты.ФИО & Студенты.№_Зач_кн & _ Студенты.Дисциплина & Студенты.Оценка
End Sub
Примечание2
В инструкции Dim переменную можно объявить с тем же именем, какое определено в пользовательском типе данных. В этом случае приведённый выше пример будет иметь вид:
Sub Пользоват_ТИП()
Dim Успеваемость As Успеваемость Успеваемость.ФИО = InputBox(«Введите ФИО») Успеваемость.№_Зач_кн = InputBox(«№_Зач_кн») Успеваемость.Дисциплина = InputBox(«Дисциплина») Успеваемость.Оценка = InputBox(«Оценка»)
20
MsgBox Успеваемость.ФИО & Успеваемость.№_Зач_кн & _ Успеваемость.Дисциплина & Успеваемость.Оценка
End Sub
Как правило, пользовательский тип данных определяется для массивов, например, так:
Dim Студенты (1 to 40) As Успеваемость
Все 40 элементов этого массива состоят из четырёх компонентов, как это указано в пользовательском типе данных Успеваемость. На конкретный элемент массива, например, первый можно сослаться следующим образом.
Студенты(1).ФИО = InputBox(«Введите ФИО») Студенты(1). №_Зач_кн = InputBox(«Введите №_Зач_кн»)
Студенты(1). Дисциплина = InputBox («Введите Дисциплина») Студенты(1). Оценка= InputBox («Введите Оценка»)
2.7.Операции VBA
Впрограммах на VBA можно использовать стандартный набор операций над данными. Имеются три основных типа операций:
математические,
отношения,
логические.
Математические операции
Операнд!] + [Операнд2] |
Сложение |
|
[ Операнд!] — [Операнд2] |
Вычитание |
|
— [Операнд] |
Перемена знака |
|
Операнд!] * [Операнд2] |
Умножение |
|
[Операнд!] / [Операнд2] |
Деление |
|
[Операнд1] [Операнд2] |
Целочисленное деление |
|
[Операнд1] Mod [Операнд2] |
Остаток от деления по модулю |
|
[Операнд1] ^ [Операнд2] |
Возведение в степень |
|
Операции отношения |
||
[Операнд1] < [Операнд2] |
Меньше |
|
[Операнд1] > [Операнд2] |
Больше |
|
[Операнд1] <= [Операнд2] |
Меньше или равно |
|
[Операнд1] >= [Операнд2] |
Больше или равно |
|
[Операнд1] <> [Операнд2] |
Не равно |
|
[Операнд1] = [Операнд2] |
Равно |
|
[Операнд1] Is [Операнд2] |
Сравнение двух операндов, содер- |
|
жащих ссылки на объекты |
||
[Операнд1] Like [Операнд2] |
Сравнение двух строковых выраже- |
|
ний |
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
6.6. Пользовательские типы данных
06-04-Пользовательские типы данных.docm — пример к п. 6.6.
Иногда возникает необходимость в работе с данными, имеющими особенную структуру. Например, какой тип должна иметь переменная, которая может хранить код пользователя, его ФИО, возраст, адрес, телефон, дату рождения? Очевидно, что встроенными типами данных тут не обойтись. Можно, конечно, представить себе строковую переменную, которая содержит все эти данные, записанные подряд, но работать с такой переменной будет очень неудобно. В подобных случаях на помощь приходят пользовательские типы данных. Для определения нового типа данных используется конструкция Type — End Type.
Рассмотрим пример. Создадим документ Microsoft Word, добавим с помощью редактора Visual Basic новый модуль и разместим в нем такой код (листинг 6.13.):
Type Worker ' начало объявления типа данных Usercode As Integer Name As String Phone As String BirthDate As Date End Type Public Sub WorkWithUser() Dim wrk_NewUser As Worker Dim wrk_TestUser As Worker Dim str_UserName As String wrk_NewUser.Usercode = 1 wrk_NewUser.Name = "Петров Петр Петрович" wrk_NewUser.Phone = "8(928)8888888" wrk_NewUser.BirthDate = #8/12/1980# 'Обмен данными между переменными 'пользовательского типа 'адекватен обычному обмену wrk_TestUser = wrk_NewUser 'Присвоим строковой переменной 'значение одной из частей 'пользовательской переменной str_UserName = wrk_TestUser.Name MsgBox ("Имя пользователя: " + str_UserName) End Sub
Листинг
6.13.
Код модуля с объявлением пользовательского типа данных
Новый тип данных должен быть объявлен вне процедуры — на уровне модуля. Мы специально привели здесь, вместе с текстом объявления типа, процедуру, в которой используется этот тип. Как видите, внутри объявления типа (между Type и End Type ), находятся объявления переменных, а сразу после ключевого слова Type следует имя типа. Мы дали типу данных имя Worker, а это значит, что объявляя переменную в модуле, мы будем использовать это имя для указания ее типа данных. Имя нашего типа данных используется при объявлении переменной точно так же, как и имена встроенных типов — String, Byte и т.д. Мы объявили три переменные. wrk_NewUser типа Worker, wrk_TestUser того же типа и str_UserName — обычную строковую переменную.
После того, как переменная типа Worker объявлена, мы можем работать с ней. А именно, обращение к элементам переменной ведется через точку с использованием имен «внутренних» переменных типа. Сначала мы по очереди присваиваем каждой части переменной wrk_NewUser соответствующие значения. Далее мы присваиваем значение переменной wrk_NewUser переменной wrk_TestUser. Как видите, работа с пользовательскими переменными одинакового типа ни чем не отличается от работы с обычными переменными. Несмотря на сложную структуру переменной, обычный оператор присваивания отлично справляется с переносом значений из одной переменной в другую. Следующий этап нашей программы — извлечение значения одной из частей переменной типа Worker, а конкретно — имени пользователя, в строковую переменную str_UserName. После этого мы выводим переменную str_UserName в окне сообщения.
6.7. Константы
06-05-Константы.docm — пример к п. 6.7.
Константы очень похожи на переменные. Они имеют имена, которые строятся по тем же правилам, в них могут храниться различные значения и т.д. Главное отличие констант от переменных в том, что константы нельзя изменять в ходе выполнения программы. Это удобно в тех случаях, когда вы собираетесь много раз использовать в программе какое-то значение и хотите, чтобы оно гарантированно оставалось неизменным.
Для объявления констант используется ключевое слово Const. При объявлении константы нужно обязательно указать ее имя и присвоить ей нужное значение. При необходимости можно указать и тип константы. Вот как выглядит работа с константами в процедуре (листинг 5.24.):
Const str_Name As String = "Александр" Const int_Size As Double = 18000 Dim num_NewSize As Double MsgBox ("Здравствуйте, " + str_Name) num_NewSize = int_Size * 2
Листинг
5.24.
Работа с константами
Здесь мы объявили пару констант — одну строковую для хранения имени пользователя, вторую — типа Double. Строковую константу мы используем для построения строки вывода в операторе MsgBox, а числовую применяем для построения выражения, результат вычислении которого записывается в переменную num_NewSize.
В VBA имеется обширный набор встроенных констант. Они используются для работы с цветом (например, vbRed — красный и т.д.) для задания типов окон сообщений и во многих других случаях. Как правило, константы, допустимые в том или ином случае, можно найти в справочном материале, который появляется при наборе команд. Так же, подробные сведения о встроенных константах содержатся в справочной системе VBA.
6.8. Выводы
В этой лекции мы завершили обсуждение основ VBA — теперь вы можете писать простые программы. Но мы еще не разговаривали о более продвинутых возможностях программирования. О них — в следующей лекции.
Type is a statement in VBA used to define variables similar to the DIM function. We may use it at the user-defined level where we have one or more values in a variable. There are two nomenclature for type statements, which are public and private. However, these are optional to use, but the variable name and the element name are required.
What is Type Statement in Excel VBA?
VBA Type Statement is used to define variables under one single group name with different data types assigned to each variable. This helps us to group together multiple variables under a single object to use them under the defined type name.
We can avoid using Class modules in VBAUsers have the ability to construct their own VBA Objects in VBA Class Modules. The objects created in this module can be used in any VBA project.read more by declaring the Type statement. It does not need any string modules because we can embed it into existing modules, saving us space.
In one of the earlier articles, we discussed the “VBA ENUMENUM or enumerations are pre-defined enumerations by users in every programming language. In VBA Vbnewline is an enumeration and we can make our own enumerations using ENUM statement.read more” to group all the variables under a single group name.
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Type (wallstreetmojo.com)
For example, if you have a group called “Mobiles,” we have group members like Redmi, Oppo, Vivo, Samsung, LG, etc. So, the Enum statement we can group with their respective values.
Enum Mobiles
Redmi = 12000
Oppo = 18000
Vivo = 18000
Samsung = 25000
LG = 15000
End Enum
Like this, we have created enumerations in that article. The problem with the Enum statement as it can hold only a LONG data type. We can use the VBA TYPE Statement to group variables with different data types. This article will show you how to construct a Type statement in VBA. Read on.
Table of contents
- What is Type Statement in Excel VBA?
- Syntax
- Type Statement Example in VBA
- VBA Types vs. VBA Class
- Recommended Articles
Syntax
Before you declare variables by using a Type statement, take a look at the syntax:
Type Group Name [Variable 1] as Variable Data Type [Variable 2] as Variable Data Type [Variable 3] as Variable Data Type [Variable 4] as Variable Data Type [Variable 5] as Variable Data Type End Type
These statements can be declared within and at the top of the module, like our Global Variables in VBA.
VBA Type can hold object variables. It can hold arrays. However, it cannot contain procedures or functions.
Type Statement Example in VBA
You can download this VBA Type Statement Template here – VBA Type Statement Template
Let us start the process of declaring variables with the Type statement. Then, we will see the same example of declaring mobile brands as we used in VBA Enum.
Step 1: At the top of the module, start the word “Type” and give a name to the Type of group.
Code:
Type MobileBrands End Type
Step 2: What are the things we usually see in mobile brands? We see names first so declare the variable as Name as String.
Code:
Type MobileBrands Name As String End Type
Step 3: After the name, we check the LaunchDate. Declare the variable as LaunchDate as Date.
Code:
Type MobileBrands Name As String LaunchDate As Date End Type
Step 4: Next, we check storage capacity to declare the variable as storage as Integer.
Code:
Type MobileBrands Name As String LaunchDate As Date Storage As Integer End Type
Step 5: The next thing is we check RAM capacity.
Code:
Type MobileBrands Name As String LaunchDate As Date Storage As RAM As Integer End Type
Step 6: At last, we check about the price.
Code:
Type MobileBrands Name As String LaunchDate As Date Storage As Integer RAM As Integer Price As Long End Type
Now, in the sub procedure, we can access all these variable data types by declaring the variable as Type, Name, i.e., MobileBrands.
Step 7: Create a subprocedure.
Code:
Sub Type_Example1() End Sub
Step 8: Now, declare the variable “Mobile” as MobileBrands.
Code:
Sub Type_Example1() Dim Mobile As Mob End Sub
Step 9: Now, with the variable name “Mobile,” we can access all the variables of “MobileBrands.”
Code:
Step 10: Now, store each value like the below.
Code:
Type MobileBrands Name As String LaunchDate As Date Storage As Integer RAM As Integer Price As Long End Type Sub Type_Example1() Dim Mobile As MobileBrands Mobile.Name = "Redmi" Mobile.LaunchDate = "10-Jan-2019" Mobile.Storage = 62 Mobile.RAM = 6 Mobile.Price = 16500 MsgBox Mobile.Name & vbNewLine & Mobile.LaunchDate & vbNewLine & _ Mobile.Storage & vbNewLine & Mobile.RAM & vbNewLine & Mobile.Price End Sub
Finally, show the result in a VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more like the below one.
Code:
Sub Type_Example1() Dim Mobile As MobileBrands Mobile.Name = "Redmi" Mobile.LaunchDate = "10-Jan-2019" Mobile.Storage = 62 Mobile.RAM = 6 Mobile.Price = 16500 MsgBox Mobile.Name & vbNewLine & Mobile.LaunchDate & vbNewLine & _ Mobile.Storage & vbNewLine & Mobile.RAM & vbNewLine & Mobile.Price End Sub
Run the code using the F5 key or manually and see the result in a message box.
Like this, we can use the VBA Type statement to define new data types in the sub procedure.
VBA Types vs. VBA Class
Often, VBA Type compares to VBA Class modules. However, there are certain differences between them. Below are the common differences.
- Difference 1: VBA Type can contain only Public variablesIn VBA, «public variables» are variables that are declared to be used publicly for all macros written in the same module as well as macros written in different modules. As a result, variables declared at the start of any macro are referred to as «Public Variables» or «Global Variables.»read more. VBA Class can contain both Public as well as Private variables.
- Difference 2: VBA Type cannot contain procedures and functions. VBA Class contains both of them along with properties.
- Difference 3: One may declare VBA Type in any modules and procedures. One can only declare VBA ClassVBA Class allows us to create our Object function to add any features, command line, function type. When created, they act like totally an independent object function but are connected.read more in dedicated class modules.
Recommended Articles
This article is a guide to VBA Type. Here, we learn how to construct a Type statement in VBA to define variables, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles:-
- VBA Data Type
- Excel VBA UCase
- Next Loop using VBA