Vba excel проверка значения на дату

Проверка переменных и выражений с помощью встроенных функций 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


Return to VBA Code Examples

IsDate Description

Returns True if the expression is a valid date. Otherwise, it returns False.

Simple IsDate Examples

Sub IsDate_Example()
    MsgBox IsDate("4/12/2019")
End Sub

This will return True.

MsgBox IsDate("4122019")

Result: False

IsDate Syntax

In the VBA Editor, you can type  “IsDate(” to see the syntax for the IsDate Function:

The IsDate function contains an argument:

Expression: An expression that will be evaluated.

Examples of Excel VBA IsDate Function

examples of various valid date:

MsgBox IsDate("8/22/2019")
MsgBox IsDate("8 22 19")
MsgBox IsDate("Aug 22 19")
MsgBox IsDate("8,22,2019")
MsgBox IsDate("8-22-19")
MsgBox IsDate("8/22")
MsgBox IsDate("8-22")

Result: True

examples of invalid date:

MsgBox IsDate("8.22.2019")
MsgBox IsDate("8222019")
MsgBox IsDate("Aug")
MsgBox IsDate("2019")

Result: False

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!

IsDate

IsDate(Expression)

Функция IsDate проверяет, является ли данное выражение корректной датой или временем. Функция обрабатывает данные любого типа без генерации ошибки. Но функция использует национальные системные установки дати и времени компьютера, поэтому «правильная» дата, полученная на одном компьютере, может оказаться некорректной на другом компьютере

Возвращаемое значение

Возвращает значение типа Boolean, показывающее, может ли значение выражения быть преобразовано в значение даты. Функция IsDate возвращает True, если выражение принадлежит к типу даты или допускает преобразование к допустимому значению даты; в противном случае возвращается False. В Microsoft Windows допустимыми являются даты в диапазоне от 1 января 100 г. до 31 декабря 9999 г.; другие операционные системы могут поддерживать другие диапазоны дат

Параметры

Expression
Обязательный аргумент — выражение типа Variant, содержащее выражение даты или строковое выражение, распознаваемое как значение даты или времени

Пример

' Используем функцию IsDate
' для проверки, является ли год высокосным
' Для этого проверяем, существует ли 29 февраля

Dim MyYear is String
If IsDate("02/29/" & myYear) Then
MsgBox myYear & "- высокосный год"
Else
MsgBox myYear & "- невысокосный год"
End If

Категория
Функции дат и времени

IsDate is the VBA function that tests whether the given value is the date or not. If the supplied value or range reference value is the date value, we will get the result as “TRUE.” On the other hand, if the value is not date, we will get the result as “FALSE.” So, the result is a BOOLEAN value, i.e., TRUE or FALSE.

Table of contents
  • Excel VBA IsDate Function
    • How to use VBA IsDate Function?
    • Things to Remember here
    • Recommended Articles

Below is the syntax of the IsDate function.

VBA IsDate Formula

The expression is nothing but the value we are trying to test, whether it is the date or not.

How to use the VBA IsDate Function?

You can download this VBA IsDate Excel Template here – VBA IsDate Excel Template

We will test whether the value “5.01.19” is a date value or not.

For this first start, the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
procedure.

Code:

Sub IsDate_Example1()

End Sub

Example 1

Define the variable to store the date value, and since the value will be the date value, assign the data type as “Date” only.

Code:

Sub IsDate_Example1()

Dim MyDate As Date

End Sub

Example 1.1

Now assign the value of “5.1.19” to the variable “MyDate.”

Code:

Sub IsDate_Example1()

Dim MyDate As Date

MyDate = "5.1.19"

End Sub

VBA IsDate Example 1.2

Open the message box in VBA now.

Code:

Sub IsDate_Example1()

Dim MyDate As Date

MyDate = "5.1.19"

MsgBox(

End Sub

 Example 1.3

In this message box, we will test whether the supplied date value to the variable “MyDate” is the date or not by using the “IsDate” function. First, open the “IsDate” function.

Code:

Sub IsDate_Example1()

Dim MyDate As Date

MyDate = "5.1.19"

MsgBox IsDate(

End Sub

VBA IsDate Example 1.4

The expression is the value we are testing to find whether it is Date or not. Since we have already stored the value to the variable “MyDate,” supply the variable name only.

Code:

Sub IsDate_Example1()

Dim MyDate As Date

MyDate = "5.1.19"

MsgBox IsDate(MyDate)

End Sub

 Example 1.5

Now run the code and see what we get in the message box.

VBA IsDate Example 1.6

The result is TRUE.

You must wonder how it recognized the value “5.1.19” as the date.

It has returned the result as TRUE because when you look at the given value “5.1.19,” it is the short form of the date “05.01.2019,” so Excel is brilliant enough to recognize it as a date, so the result is TRUE.

 Example 1.7

Now here comes the tricky thing, for the same value, what we will do is we will change the short form of the year from 19 to 2019.

Code:

Sub IsDate_Example1()

Dim MyDate As String

MyDate = "5.1.2019"

MsgBox IsDate(MyDate)

End Sub

Example 2.0

Now, run the code and see the result.

VBA IsDate Example 2.1

This time it has returned the result as FALSE because the “day and month” portion of the date is in short form, but the year part is in full form of “YYYY,” so ISDATE cannot recognize it has a date, so the result is FALSE.

Now, look at the code below.

Code:

Sub IsDate_Example1()

Dim MyDate As String

MyDate = "05.01.2019"

MsgBox IsDate(MyDate)

End Sub

 Example 2.2

We have mentioned a full day and full month format by using 0. Let us run the code and see the result of the IsDate function.

This time also we go got the result as FALSE.

VBA IsDate Example 2.3

Now, change the code as follows.

Code:

Sub IsDate_Example1()

Dim MyDate As String

MyDate = "05/01/2019"

MsgBox IsDate(MyDate)

End Sub

 Example 2.4

Instead of the dot (.) as the separator, we have entered forward-slash (/) as the separator. Now run the code and see the result.

VBA IsDate Example 2.5

This time we got the result as TRUE.

We have told you at the beginning of the article that “Date” is a sensitive thing.

Now what we will do is we will merge the date and time.

Code:

Sub IsDate_Example1()

Dim MyDate As String

MyDate = "05/01/2019 15:26:24"

MsgBox IsDate(MyDate)

End Sub

 Example 2.6

We have added above the time portion of “15:26:24” in front of the date. Now, run the code and see the result.

VBA IsDate Example 2.7

This time, we also got the result TRUE because DATE and TIME in Excel are the same things and stored as serial numbers. The whole number represents the date portion, and decimal places represent the time portion.

Things to Remember here

  • The IsDate function returns the Boolean type result, i.e., TRUE or FALSE.
  • The IsDate function is available only as a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more.
  • Only valid formatted dates one can treat as the date. Else, it will treat as text values and return the result as FALSE.

Recommended Articles

This article has been a guide to VBA IsDate. Here, we discuss how to use the VBA IsDate function to check whether a given value is a date or not, along with the example and downloadable Excel sheet. Below are some useful Excel articles related to VBA: –

  • VBA Randomize
  • Steps to Create Login Form in VBA
  • VBA Month
  • DatePart Function in VBA
  • VBA RegEx

VBA IsDate function in Excel is categorized as an Information function in VBA. It is a built-in function in MS Office Excel VBA. Checks specified Expression or Variant is Date or not. It has one input parameter. Returns a Boolean value (True or False). If specified variant is valid Date then it returns True, Otherwise it returns False.

We can’t use this function as a worksheet function. We can only use as a VBA function. This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA IsDate function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the IsDate function, where we can use this VBA IsDate function and real-time examples.

Table of Contents:

  • Overview
  • Syntax of VBA IsDate Function
  • Parameters or Arguments
  • Where we can apply or use VBA IsDate Function?
  • Example 1: Check an expression(VBAF1.COM) is Date or not
  • Example 2: Check given expression(12345) is Date or not
  • Example 3: Check an expression(12:12:12 PM) is Date or not
  • Example 4: Check an expression(Jan 01, 2018) is Date or not
  • Example 5: Check a variable(01/01/2018 12:12 PM) is Date or not
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA IsDate function is

IsDate(Expression)

The VBA IsDate function returns a boolean value either True or False.

Parameters or Arguments

The IsDate function has one input parameter or argument.
Where
Expression: It is a required parameter. The Expression that you want to evaluate. It could be a date or time or a string in a date format

Where we can apply or use VBA IsDate Function?

We can use this VBA IsDate function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Check an expression(VBAF1) is Date or not

Here is a simple example of the VBA IsDate function. This below example checks the specified string(VBAF1) is Date or not. The output of below macro is FALSE.

'Check an expression(VBAF1) is Date or not
Sub VBA_IsDate_Function_Ex1()
    
    'Variable declaration
    Dim iExpression As String
    Dim sOutput As Boolean
    
    iExpression = "VBAF1"
    
    sOutput = IsDate(iExpression)
   
    'Display output message
    MsgBox "The expression('VBAF1') is Date or not : " & sOutput, vbInformation, "VBA IsDate Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA IsDate Function

Example 2: Check given expression(12345) is Date or not

Here is another example of the VBA IsDate function. This below example checks the specified number(12345) is Date or not. The output of below macro is FALSE.

'Check given expression(12345) is Date or not
Sub VBA_IsDate_Function_Ex2()
    
     'Variable declaration
    Dim iExpression As Integer
    Dim sOutput As Boolean
    
    iExpression = 12345
    
    sOutput = IsDate(iExpression)
   
    'Display output message
    MsgBox "The expression(12345) is Date or not : " & sOutput, vbInformation, "VBA IsDate Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA IsDate Function

Example 3: Check an expression(12:12:12 PM) is Date or not

Here is a simple example of the VBA IsDate function. This below example checks the specified variable(12:12:12 PM) is Date or not. This function considers time as date variable. The output of below macro returns TRUE.

'Check an expression(12:12:12 PM) is Date or not
Sub VBA_IsDate_Function_Ex3()
    
   'Variable declaration
    Dim iExpression As Date
    Dim sOutput As Boolean
    
    iExpression = "12:12:12 PM"
    
    sOutput = IsDate(iExpression)
   
    'Display output message
    MsgBox "The expression(12:12:12 PM) is Date or not : " & sOutput, vbInformation, "VBA IsDate Function"
    
End Sub

Output:Here is the screen shot of the third example output.
VBA IsDate Function

Example 4: Check an expression(Jan 01, 2018) is Date or not

Here is a simple example of the VBA IsDate function. This below example checks the specified variable(Jan 01, 2018) is date or not. The output of below macro is TRUE.

'Check an expression(Jan 01, 2018) is Date or not
Sub VBA_IsDate_Function_Ex4()
    
    'Variable declaration
    Dim iExpression As Date
    Dim sOutput As Boolean
    
    iExpression = "Jan 01, 2018"
    
    sOutput = IsDate(iExpression)
   
    'Display output message
    MsgBox "The expression(Jan 01, 2018) is Date or not : " & sOutput, vbInformation, "VBA IsDate Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA IsDate Function

Example 5: Check a variable(01/01/2018 12:12 PM) is Date or not

Here is a simple example of the VBA IsDate function.This below example checks the specified undeclared variable is Date or not. The output of below macro is TRUE.

'Check a variable(01/01/2018 12:12 PM) is Date or not
Sub VBA_IsDate_Function_Ex5()
    
    'Variable declaration
    Dim iExpression As Date
    Dim sOutput As Boolean
    
    iExpression = "01/01/18 12:12 PM"
       
    sOutput = IsDate(iExpression)
   
    'Display output message
    MsgBox "The expression(01/01/18 12:12 PM) is Date or not : " & sOutput, vbInformation, "VBA IsDate Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA IsDate Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

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