Vba excel проверка типов данных

В языке VBA есть универсальные типы данных, т.е. способные хранить как число, так и строку, дату и любой другой тип информации. Например, ячейка в таблице может содержать что угодно и изначально, программа не знает какой в ней тип данных хранится. Кроме того, в самой программе может использоваться тип данных Variant, который так же может содержать любое значение любого типа.

Чтобы определить какой тип данных в ячейке или в переменной типа Variant, можно воспользоваться несколькими способами.

Способ 1. Использовать функцию TypeName для определения типа данных

Эта функция возвращает строку с названием типа данных на английском. В качестве аргумента принимает переменную, значение ячейки.
Обратите внимание: Функция определяет только стандартные типы данных и не может определить пользовательский тип (определенный с помощью Type).

Возможные возвращаемые функцией значения:

Byte Число типа Byte
Integer Целое число
Long Длинное целое число
Single Число одиночной точности с плавающей запятой
Double Число двойной точности с плавающей запятой
Currency Валюта
Decimal Число с плавающей запятой
Date Дата
String Строка
Boolean Логическое
Error Ошибка
Empty Не проинициализировано (т.е. переменная не была объявлена)
Null Неверные данные (в переменной нет корректных данных)
Object Объект (класс)
Unknown Тип данных не известен
Nothing Объект, никуда не ссылающийся

Приведу несколько примеров по использованию TypeName.

Пример 1. Определение типа переменной.

Dim v As Integer
MsgBox TypeName(v) ' Выведет: Integer

Обратите внимание: если вы используете результат TypeName в условии, т.е. проверяете, соответствует ли тип данных определенному, например, Integer, то регистр символов возвращаемого типа имеет значение. Т.е. нужно писать Integer с заглавной буквы, либо использовать приведение всех символов к одному регистру.

Пример 2. Использование TypeName в условии.

Dim v As Integer
If TypeName(v) = "Integer" Then MsgBox "Yes" Else MsgBox "No"         ' Yes
If TypeName(v) = "integer" Then MsgBox "Yes" Else MsgBox "No"         ' No
If LCase(TypeName(v)) = "integer" Then MsgBox "Yes" Else MsgBox "No"  ' Yes

Пример 3. Определение типа данных в ячейке.

MsgBox TypeName(Cells(1, 1).Value) ' Выведет тип данных в ячейке A1

Если функции была передана переменная массив, она вернет тип данных в массиве с добавлением скобок.

Пример 4. Определение типа массива.

Dim Arr1(10) As Integer
Dim Arr2(10)
MsgBox TypeName(Arr1) ' Выведет: Integer()
MsgBox TypeName(Arr2) ' Выведет: Variant()

Способ 2. Проверка на возможность преобразования строки к нужному типу.

Бывает ситуация, когда значение, например, число или дата, содержится в строке. В этом случае TypeName вернет String, а не Integer или Date. Чтобы узнать, что содержится в строке, можно воспользоваться одной из функций IsNumeric, IsDate, IsObject, IsArray, IsNull, IsError.

IsNumeric Проверяет может ли выражение быть преобразовано в число
IsDate Проверяет может ли выражение быть преобразовано в дату
IsObject Проверяет, является ли переменная объектом
IsArray Проверяет, является ли переменная массивом
IsNull Проверка на пустое значение
IsError Проверка выражения на ошибку

Пример 4. Определение может ли переменная быть преобразована в число.

Dim v As String
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no (т.к. в строке нет числа)
v = "120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
v = "120.45"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "test 120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "120 test"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

К сожалению, как видим из примера, нет возможности проверить, содержится ли в строке число с плавающей точкой.

Пример 5. Определение содержит ли переменная дату (может быть преобразована в дату).

Dim firstDate, secondDate As Date
Dim timeOnly, dateAndTime, noDate As String
firstDate = CDate("12.05.2017")
secondDate = #12/5/2017#
timeOnly = "15:45"
dateAndTime = "12.05.2017 15:45"
noDate = "Test"
If IsDate(firstDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(secondDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(timeOnly) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(dateAndTime) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(noDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

Проверка, содержится ли число или дата в ячейке листа делается аналогично, как и с переменными.

Помимо этих способов можно конечно еще придумать и другие, например, проверку строки с данными регулярным выражением или пройти по каждому символу в цикле и проверить цифра это или нет и тому подобное. Но на мой взгляд, описанных мной способов вполне достаточно для решения повседневных задач.

Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.

Проверка переменных и выражений

Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.

Синтаксис функций для проверки переменных и выражений:

Expression — выражение, переменная или необязательный аргумент для IsMissing.

Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.

Функция IsArray

Описание функции

Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:

  • True — переменная является массивом;
  • False — переменная не является массивом.

Пример с IsArray

Sub Primer1()

Dim arr1(), arr2(1 To 10), arr3

    Debug.Print IsArray(arr1)  ‘Результат: True

    Debug.Print IsArray(arr2)  ‘Результат: True

    Debug.Print IsArray(arr3)  ‘Результат: False

arr3 = Array(1, 2, 3, 4, 5)

    Debug.Print IsArray(arr3)  ‘Результат: True

End Sub

Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.

Функция IsDate

Описание функции

Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:

  • True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
  • False — в иных случаях.

Пример с IsDate

Sub Primer2()

Dim d1 As String, d2 As Date

    Debug.Print IsDate(d1)  ‘Результат: False

    Debug.Print IsDate(d2)  ‘Результат: True

d1 = «14.01.2023»

    Debug.Print IsDate(d1)  ‘Результат: True

    Debug.Print IsDate(Now)  ‘Результат: True

End Sub

Функция IsEmpty

Описание функции

Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:

  • True — переменная содержит значение Empty;
  • False — переменной присвоено значение, отличное от Empty.

Пример с IsEmpty

Sub Primer3()

Dim s As String, v As Variant

    Debug.Print IsEmpty(s)  ‘Результат: False

    Debug.Print IsEmpty(v)  ‘Результат: True

v = 125

    Debug.Print IsEmpty(v)  ‘Результат: False

Range(«A1»).Clear

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: True

Range(«A1») = 123

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: False

End Sub

Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).

Функция IsError

Описание функции

Функция IsError возвращает логическое значение, указывающее, является ли аргумент функции значением ошибки, определенной пользователем:

  • True — аргумент функции является значением ошибки, определенной пользователем;
  • False — в иных случаях.

Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.

Пример с IsError

Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:

Function Vkuba(x)

    If IsNumeric(x) Then

        Vkuba = x ^ 3

    Else

        Vkuba = CVErr(25)

    End If

End Function

Sub Primer4()

    Debug.Print Vkuba(5)  ‘Результат: 125

    Debug.Print IsError(Vkuba(5))  ‘Результат: False

    Debug.Print Vkuba(«пять»)  ‘Результат: Error 25

    Debug.Print IsError(Vkuba(«пять»))  ‘Результат: True

End Sub

Функция IsMissing

Описание функции

Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:

  • True — если в процедуру не было передано значение для необязательного аргумента;
  • False — значение для необязательного аргумента было передано в процедуру.

Пример с IsMissing

Function Scepka(x, Optional y)

    If Not IsMissing(y) Then

        Scepka = x & y

    Else

        Scepka = x & » (а необязательный аргумент не подставлен)»

    End If

End Function

Sub Primer5()

    Debug.Print Scepka(«Тропинка», » в лесу»)  ‘Результат: Тропинка в лесу

    Debug.Print Scepka(«Тропинка»)  ‘Результат: Тропинка (а необязательный аргумент не подставлен)

End Sub

Функция IsNull

Описание функции

Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:

  • True — значением переменной или выражения является Null;
  • False — в иных случаях.

Пример с IsNull

Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:

Sub Primer6()

Dim Var

Var = Null

    If Var = Null Then Debug.Print Var  ‘Результат: «»

    If Var <> Null Then Debug.Print Var  ‘Результат: «»

    If IsNull(Var) Then Debug.Print Var  ‘Результат: Null

End Sub

Функция IsNumeric

Описание функции

Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:

  • True — если аргумент функции может рассматриваться как число;
  • False — в иных случаях.

Пример с IsNumeric

Sub Primer7()

Debug.Print IsNumeric(«3,14»)  ‘Результат: True

Debug.Print IsNumeric(«четыре»)  ‘Результат: False

End Sub

Функция IsObject

Описание функции

Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:

  • True — переменная содержит ссылку на объект или значение Nothing;
  • False — в иных случаях.

Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.

Пример с IsObject

Sub Primer8()

Dim myObj As Object, myVar As Variant

    Debug.Print IsObject(myObj)  ‘Результат: True

    Debug.Print IsObject(myVar)  ‘Результат: False

Set myVar = ActiveSheet

    Debug.Print IsObject(myVar)  ‘Результат: True

End Sub


I want to check Data in all excel sheet column to ensure that data is as per its specified data type.

Like in a numeric column there should not be char value.

Thanks in Advance.

Luuklag's user avatar

Luuklag

3,90711 gold badges39 silver badges57 bronze badges

asked Apr 4, 2014 at 14:26

Anuj's user avatar

Yes, use the same functions as you would in Visual Basic. isdate, isnumeric, etc. Make sure you test your data some. Some of the data type checker functions are not fool-proof, especially isnumeric. Here is one related thread to that Wrong result from IsNumeric() in VB.NET

There are many more out there if you search.

Community's user avatar

answered Apr 4, 2014 at 15:12

Alan Waage's user avatar

Alan WaageAlan Waage

6034 silver badges12 bronze badges

As mentioned in the other post, Excel has some built in functions which allow you to test data in a field. This works great for the front end. It should also be noted that the datatypes available in the front end Excel are not the same datatypes available in the backend VBA (they are similar but different).

Datatypes in VBA in the backend can be trickier than other languages for two reasons: 1) The Variant datatype (which is a nondescript datatype) and 2) VBA doesn’t by default require you to specify the datatype of a variable (it will try and guess what you meant unless you use the Option Explicit command).

Check out the following articles on available VBA datatypes and converting between them:

  • Data Type Summary
  • Type Conversions in VB
  • Variant Data Type

answered Apr 4, 2014 at 15:21

Return to VBA Code Examples

This article will demonstrate the use of the VBA TypeOf Operator.

The VBA TypeOf Operator is used in determining the type of an object. This can be useful in enabling or disabling controls on a VBA form or to control the flow of code depending on what type of object is being used.

Using TypeOf to Control Code

We can use TypeOf to ensure that the selection made is the type of specific object that we require – for example, we may want to select a range and then use an IF statement to see what is selected.  If a range is selected, then we we will get a message telling us that a range is selected, but if a range is not selected, we will get a different message.

Let us select some cells on our worksheet.

VBA Text TypeOf Select Range

Now, if we run the macro below, we will be told that we selected a Range.

Sub TestSelection()
  Dim rng As Object
  If TypeOf Selection Is Range Then
     MsgBox "A range has been selected!"
  Else
     MsgBox "Something else is selected"
  End If
End Sub

VBA Text TypeOf Select Range_Msg

However, if we do not select a range and select something else – perhaps a chart – and then run the macro, we will get a different result!

VBA Text TypeOf Select Chart Msg

Using TypeOf on Form Controls

VBA enables us to create interactive forms that the user can fill in and return data to the code to be used in various ways.  We can use the TypeOf operator to determine the type of controls that are being used on a form.

In the example below, I have created a user form with a variety of controls on it – a couple of Text Boxes, a Combo Box, 2 option buttons, 2 check boxes and 3 command buttons.

VBA Text TypeOf Form Intro

Using the code below, I can determine what type of controls are on the form by looping through all the controls on the form.   I have used the TypeName function to return a message with the type of the control, and have used a VBA IF Statement using the TypeOf function  to check what type of control is selected, and then a further message box to return that type of control.

Sub WhatControlType()
  Dim ctl As Object
  For Each ctl In Me.Controls
    MsgBox (TypeName(ctl))
'Use the TypeOf function to determine the object's type.
    If TypeOf ctl Is msforms.TextBox Then
      MsgBox ("The control is a TextBox.")
    ElseIf TypeOf ctl Is msforms.ComboBox Then
      MsgBox ("The control is a ComboBox.")
    ElseIf TypeOf ctl Is msforms.Label Then
      MsgBox ("The control is a Label.")
    ElseIf TypeOf ctl Is msforms.CommandButton Then
      MsgBox ("The control is a Command Button.")
    ElseIf TypeOf ctl Is msforms.CheckBox Then
      MsgBox ("The control is a Check Box.")
    ElseIf TypeOf ctl Is msforms.OptionButton Then
      MsgBox ("The control is an Option/Radio Button.")
    Else
      MsgBox ("The object is some other type of control.")
    End If
Next ctl
End Sub

This type of code can be very useful if we wish to enable or disable controls.   In the code below, when the form is first opened, the option buttons and check boxes are disabled.

Private Sub UserForm_Initialize()
  Dim ctl As Object
  For Each ctl In Me.Controls
     If TypeOf ctl Is msforms.CheckBox Then
        ctl.Enabled = False
     ElseIf TypeOf ctl Is msforms.OptionButton Then
        ctl.Enabled = False
     Else
        ctl.Enabled = True
     End If
   Next ctl
End Sub

VBA Text TypeOf_Form

To enable the option buttons and checkboxes, I have written some further code behind the Enable Controls button.

Private Sub cmdEnable_Click()
  Dim ctl As Object
  For Each ctl In Me.Controls
    If TypeOf ctl Is msforms.CheckBox Then
      ctl.Enabled = Not ctl.Enabled
    ElseIf TypeOf ctl Is msforms.OptionButton Then
      ctl.Enabled = Not ctl.Enabled
    End If
  Next ctl
End Sub

Now when we click on the Enable Controls button, if the controls are disabled, they will become enabled and if they are enabled they will become disabled.  This is achieved using the Not Operator which enables us to toggle between disabled and enabled.

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!
vba save as

Learn More!

Dear Friends,
Some time during the VBA programming you may need to perform different action based on “what is the type of the variable” you are dealing with. Or in other words what kind of data is stored in a variable. In VBA, if you have not defined type of a variable while declaring it using “Dim statement”, then whatever value you assign to that variable, data type of the value is inherited by the variable.

How to find the Data Type of a Variable

How to find the Data Type of a Variable

Get the data type of a Variable in VBA

VarTpe(YourVariable) is a VBA function which

1. Takes your variable name as input parameter
2. Returns the data type of the variable or type of the data stored in this variable.

How to use VarType() VBA function

In the below example, code VBA.VarType(varString) will return 8. This is the return value for String Type variable. Refer the below table for return value for all the data types.


Sub GetTypeOfAllVariables()
    Dim varString As String
    MsgBox "Data Type of the Variable varString is : " &amp; VBA.VarType(varString)
End Sub

Data Types and their Return Value

Variable Type Return Value
Variant 0
Integer 2
Long 3
Single 4
Double 5
Currency 6
Date 7
String 8
Boolean 11
Byte 17

As I mentioned above, this function does not return the variable type what is defined but also based on what kind of value it has stored in it. This is quite possible that a variable defined as Variant is holding a NULL value or Nothing or Empty etc. These are special cases where VBA returns different values based on the data which this Variant variable is holding.

Where should I use this?

In VBA, it is possible to define a variable without any type (default type = Variant). This variable will keep changing its type based on the value assigned to it during run time. Then sometime, during programming it will become important to know what kind of data it has got at this moment before I perform any operation on it.

More about VarType Function

As I believe that Microsoft Excel VBA help is really rich. You should always start with the help provided there. It is available offline as well which is the best part of it. Therefore make use of it in learning VBA.
To know more about these return values which I have not specified here you can get them here:

varType - VBA Function

varType – VBA Function

Понравилась статья? Поделить с друзьями:
  • Vba excel проверка существования объекта
  • Vba excel проверка символа в ячейке
  • Vba excel проверка объединения ячеек
  • Vba excel проверка на целое число
  • Vba excel проверка на пустую строку