Excel vba if value is date

  • Remove From My Forums
  • Question

  • Hi All,

    I want to check range of cells and want to allow only dates in them entered in mm/dd/yyyy format. I tried applying excel data validation but it also excepts if i enter date as 1/1 (no year entered or 1 Jan)

    I also tried below code but it also do not throw error if date in entered without year like 1/1 or 1 Jan

    Private Sub Worksheet_Activate()
    If Not IsDate(ActiveSheet.Range("A1").Value) And ActiveSheet.Range("A1").NumberFormat <> "m/d/yyyy" Then
    MsgBox "Date is not valid"
    End If
    
    End Sub

    I want code to check 2 things.

    1. value in cell must be date and
    2. date must be in MM/DD/YYYY format
    3. even if that cell is blank than error msg box shall pop up.

    Thanks,

    Zaveri

    • Edited by

      Wednesday, April 1, 2015 1:38 PM

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

Содержание

  1. VBA IsDate Function
  2. IsDate Description
  3. Simple IsDate Examples
  4. IsDate Syntax
  5. Examples of Excel VBA IsDate Function
  6. VBA Coding Made Easy
  7. VBA Code Examples Add-in
  8. VBA Code Generator
  9. AutoMacro: VBA Add-in with Hundreds of Ready-To-Use VBA Code Examples & much more!
  10. What is AutoMacro?
  11. VBA Excel. Проверка переменных и выражений
  12. Проверка переменных и выражений
  13. Функция IsArray
  14. Описание функции
  15. Пример с IsArray
  16. Функция IsDate
  17. Описание функции
  18. Пример с IsDate
  19. Функция IsEmpty
  20. Описание функции
  21. Пример с IsEmpty
  22. Функция IsError
  23. Описание функции
  24. Пример с IsError
  25. VBA Excel. Функции для работы с датой и временем
  26. Функция Date
  27. Функция DateAdd
  28. Функция DateDiff
  29. validating date in excel VBA
  30. sankar_bhatta
  31. Excel Facts
  32. Tom Urtis
  33. sankar_bhatta
  34. sankar_bhatta
  35. Tom Urtis
  36. VBA Date Functions
  37. VBA Date Function
  38. VBA Now Function
  39. VBA Time Function
  40. VBA DateAdd Function
  41. VBA DateDiff Function
  42. VBA DatePart Function
  43. VBA Coding Made Easy
  44. VBA DateSerial Function
  45. VBA DateValue Function
  46. VBA Day Function
  47. VBA Hour Function
  48. VBA Minute Function
  49. VBA Second Function
  50. VBA Month Function
  51. VBA MonthName Function
  52. VBA TimeSerial Function
  53. VBA TimeValue Function
  54. VBA Weekday Function
  55. VBA WeekdayName Function
  56. VBA Year Function
  57. Comparing Dates in VBA
  58. VBA Code Examples Add-in

VBA IsDate Function

In this Article

IsDate Description

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

Simple IsDate Examples

This will return True.

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:

examples of invalid date:

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 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!)

VBA Code Generator

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.

Источник

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

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

Функция IsDate

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

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

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

Пример с IsDate

Функция IsEmpty

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

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

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

Пример с IsEmpty

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

Функция IsError

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

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

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

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

Пример с IsError

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

Источник

VBA Excel. Функции для работы с датой и временем

Функции для работы с датой и временем в VBA Excel. Синтаксис, параметры, спецсимволы, примеры. Функции, возвращающие текущие дату и время по системному таймеру.

Функция Date

Синтаксис

Пример

Функция DateAdd

Синтаксис

Параметры

Параметр Описание
interval Обязательный параметр. Строковое выражение из спецсимволов, представляющее интервал времени, который требуется добавить.
number Обязательный параметр. Числовое выражение, задающее количество интервалов, которые необходимо добавить. Может быть как положительным (возвращается будущая дата), так и отрицательным (возвращается предыдущая дата).
date Обязательный параметр. Значение типа Variant/Date или литерал, представляющий дату, к которой должен быть добавлен интервал.

Таблицу аргументов (значений) параметра interval смотрите в параграфе «Приложение 1».

Примечание к таблице аргументов: три символа – y, d, w – указывают функции DateAdd на один день, который необходимо прибавить к исходной дате number раз.

Пример

Функция DateDiff

Синтаксис

Параметры

Параметр Описание
interval Обязательный параметр. Строковое выражение из спецсимволов, представляющее интервал времени, количество которых (интервалов) требуется вычислить между двумя датами.
date1, date2 Обязательные параметры. Значения типа Variant/Date , представляющие две даты, между которыми вычисляется количество указанных интервалов.
firstdayofweek Необязательный параметр. Константа, задающая первый день недели. По умолчанию – воскресенье.
firstweekofyear Необязательный параметр. Константа, задающая первую неделю года. По умолчанию – неделя, в которую входит 1 января.

Таблицу аргументов (значений) параметра interval смотрите в параграфе «Приложение 1».

Примечание к таблице аргументов: в отличие от функции DateAdd , в функции DateDiff спецсимвол «w» , как и «ww» , обозначает неделю. Но расчет осуществляется по разному. Подробнее об этом на сайте разработчиков.

Параметры firstdayofweek и firstweekofyear определяют правила расчета количества недель между датами.

Таблицы констант из коллекций firstdayofweek и firstweekofyear смотрите в параграфах «Приложение 2» и «Приложение 3».

Источник

validating date in excel VBA

sankar_bhatta

New Member

i am a newbie to VBA and find thread on this forum very helpful. I am developing a macro to validate soem fields in excel. one of the column in this excel can haev a date type of data( please note the format of this field is not date ).
I am reading the whole data of the excel into a array of type VARIANT. i am then passing the specific columns to another sub where I am using IsDate function to validate if this ia date. But the function IsDate is always returning false

I tried CDate etc. but nothing seems to work

Sub Validate_Contracts_EffectiveDate(par1 As Variant)
If IsDate(par1) = False Then
lv_error = True
lv_err_text = «only date format is allowed»
End If
end Sub

Excel Facts

Tom Urtis

MrExcel MVP

Just thinking out loud, it might be that what you think is a valid date entry is not what Excel thinks is a valid date entry. For example, if in some cell you enter
May 5 2021
Excel will regard that as a text entry no matter what verification function you try to use.

Or there might be some other factor at play, such as a cell formatted beforehand as text, or a stray invisible character in the cell. Post back with an exact (exact means exact) example of a cell value in your workbook that is believed (by looking at it) to be a date, and maybe someone will notice what’s wrong or recommend an alternative verification method.

sankar_bhatta

New Member

Just thinking out loud, it might be that what you think is a valid date entry is not what Excel thinks is a valid date entry. For example, if in some cell you enter
May 5 2021
Excel will regard that as a text entry no matter what verification function you try to use.

Or there might be some other factor at play, such as a cell formatted beforehand as text, or a stray invisible character in the cell. Post back with an exact (exact means exact) example of a cell value in your workbook that is believed (by looking at it) to be a date, and maybe someone will notice what’s wrong or recommend an alternative verification method.

this is how the excel column looks like. I have entered some valid dates and some invalid dates like 45.03.2021. In my code, I am first reading all the data in the excel into an array of type variant

iRowsCount = lv_ws.Range(«A» & lv_ws.Rows.Count).End(xlUp).Row

Set rngSource = lv_ws.Range(«A2:AN» & iRowsCount)
Set file_Ctr_Columns = lv_ws.Range(«A1:AN1»)
gv_column_no = rngSource.Columns.Count
ReDim gv_ctr_tab(1 To rngSource.Rows.Count, 1 To rngSource.Columns.Count)

here gv_ctr_tab contains all the data of the all cells

then i am calling a annother sub passing individual cells to validate

Call Validate_Custom_Fields(gv_ctr_tab(x, y), lv_column_name, lv_cus_count)

with in this sub I have sevral subs which validate the data of each cell depending on type of data

Sub Validate_Custom_Fields(par1 As Variant, par2 As String, par3 As Integer)
‘Par1 is value of column in contract template excel
‘Par2 is column name
‘Par3 is row number of cusomt field in Custom_fields tab

Dim lv_string As String
‘List values
lv_string = gv_cust_tab(par3, 3)

‘Field type
Select Case gv_cust_tab(par3, 2)

Call Validate_Boolean(par1, par2)

Call Validate_Date(par1, par2)

Call Validate_ListValues(par1, par2, lv_string)

Call Validate_Numeric(par1, par2)

the problem is with in Validate_Date sub

Sub Validate_Date(par1 As Variant, par2 As String)

Dim lv_err_text As String
Dim lv_error As Boolean
Dim i As Integer
Dim lv_date_string As String
Dim lv_date As Date

If IsDate(par1) = True Then
Else
lv_error = True
lv_err_text = «Please enter valid date for this custom field»
End If

sankar_bhatta

New Member

Any Ideas or suggestions for me?

Tom Urtis

MrExcel MVP

When I enter in my Excel worksheet these examples such as you posted.
in cell A1, 12.03.2021
in cell A2, 03.31.2021
in cell A3, 12.03.2121
. these are all text entries, as I suspected when I first wrote:
«it might be that what you think is a valid date entry is not what Excel thinks is a valid date entry.»

I do not know what you are actually doing or what you want. The next entry in your pictured example is
45.03.2021
and that is a text value regardless of a date format being mmddyyy or ddmmyyyy.

So maybe your task at hand is to determine if such an entry is or is not a date if it could be formatted as a date. Recall that formatting a cell only affects how the entry looks to the human eye; it does not change the underlying cell value.

You are still left with the precedent task of changing those intervening period (or dot) characters to a forward slash or a dash character, which, when adding a zero to that, will change that item to a bona fide date, if the entry can possibly be a date.

To do that with a formula, for example, can be this:

In column AB In a different column enter: Returning
1 cus_Segmentation
2 12.03.2021 =SUBSTITUTE(AB2,».»,»/»)+0 44533
3 03.31.2021 =SUBSTITUTE(AB3,».»,»/»)+0 44286
4 12.03.2121 =SUBSTITUTE(AB4,».»,»/»)+0 81057
5 45.03.2021 =SUBSTITUTE(AB5,».»,»/»)+0 #VALUE!
6 12.34.2021 =SUBSTITUTE(AB6,».»,»/»)+0 #VALUE!
7 12.03.2021 =SUBSTITUTE(AB7,».»,»/»)+0 44533

From there it is a simple matter of selecting the formula cells and formatting them in your desired date format, and probably paste special them as values too.

The issue remains as to what you want to do about the #VALUE! returns, maybe delete those records (rows) but that it is up to you.

To do it using VBA, using column AB as the location of the date-like original values in your picture, can be this macro:

You will end up with this:

In column AB
1 cus_Segmentation
2 12/3/2021
3 3/31/2021
4 12/3/2121
5 45/03/2021 is not a date.
6 12/34/2021 is not a date.
7 12/3/2021

Источник

VBA Date Functions

In this Article

This tutorial will cover the different built-in VBA Date Functions.

VBA Date Function

You can use the Date Function to return the current date.

The syntax of the Date Function is Date(). It has no arguments.

The following code shows you how to use the Date Function:

The result shown in the Immediate Window is:

VBA Now Function

You can use the Now Function to return the current date and time.

The syntax of the Now Function is Now(). It has no arguments.

The following code shows you how to use the Now Function:

VBA Time Function

You can use the Time Function to return the current time.

The syntax of the Time Function is Time(). It has no arguments.

The following code shows you how to use the Time Function:

VBA DateAdd Function

You can use the DateAdd Function to add a date/time interval to a date or time, and the function will return the resulting date/time.

The syntax of the DateAdd Function is:

DateAdd(Interval, Number, Date) where:

  • Interval – A string that specifies the type of interval to use. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Number – The number of intervals that you want to add to the original date/time.
  • Date – The original date/time.

Note: When using dates in your code you have to surround them with # or quotation marks.

The following code shows how to use the DateAdd Function:

VBA DateDiff Function

You can use the DateDiff Function in order to get the difference between two dates, based on a specified time interval.

The syntax of the DateDiff Function is:

DateDiff(Interval, Date1, Date2, [Firstdayofweek], [Firstweekofyear]) where:

  • Interval – A string that specifies the type of interval to use. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Date1 – A date value representing the earlier date.
  • Date2 – A date value representing the later date.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

  • Firstweekofyear (Optional) – A constant that specifies the first week of the year. If blank then the Jan 1st week is used as the first week of the year. Firstweekofyear can be one of the following values:

-vbFirstJan1 – uses the week containing Jan 1st.
-vbFirstFourDays – uses the first week that contains at least four days in the new year.
-vbFirstFullWeek – uses the first full week of the year.
-vbSystem – uses the first week of the year as specified by your system settings.

The following code shows you how to use the DateDiff Function:

VBA DatePart Function

You can use the DatePart Function in order to return a part (day, week, quarter, month etc.) of a given date.

The syntax of the DatePart Function is:

DatePart(Interval, Date,[Firstdayofweek], [Firstweekofyear]) where:

  • Interval – A string that specifies the part of the date to return. The interval can be one of the following values:

“d” – day
“ww” – week
“w” – weekday
“m” – month
“q” – quarter
“yyyy” – year
“y” – day of the year
“h” – hour
“n” – minute
“s” – second

  • Date – The date that you want the function to return a part of.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

  • Firstweekofyear (Optional) – A constant that specifies the first week of the year. If blank then the Jan 1st week is used as the first week of the year. Firstweekofyear can be one of the following values:

-vbFirstJan1 – uses the week containing Jan 1st.
-vbFirstFourDays – uses the first week that contains at least four days in the new year.
-vbFirstFullWeek – uses the first full week of the year.
-vbSystem – uses the first week of the year as specified by your system settings.

The following code shows you how to use the DatePart Function:

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 DateSerial Function

The VBA DateSerial Function takes an input year, month and day and returns a date.

The syntax of the DateSerial Function is:

DateSerial(Year, Month, Day) where:

  • Year – An integer value between 100 and 9999 that represents the year.
  • Month – An integer value that represents the month.
  • Day – An integer value that represents the day.

The following code shows you how to use the DateSerial Function:

VBA DateValue Function

The DateValue Function returns a Date when given a string representation of a date.

The syntax of the DateValue Function is:

  • Date – A String representing the date.

The following code shows you how to use the DateValue Function:

VBA Day Function

You can use the Day Function to return the day of an input date.

The syntax of the Day Function is:

  • Date_value – The date which you want to extract the day from.

The following code shows you how to use the Day Function:

VBA Hour Function

You can use the Hour Function to return the hour of an input time.

The syntax of the Hour Function is:

  • Time – The time that you want to extract the hour from.

The following code shows you how to use the Hour Function:

VBA Minute Function

You can use the Minute Function to return the minute value of an input time.

The syntax of the Minute Function is:

  • Time – The time that you want to extract the minute value from.

The following code shows you how to use the Minute Function:

VBA Second Function

You can use the Second Function to return the second value of an input time.

The syntax of the Second Function is:

  • Time – The time that you want to extract the second value from.

The following code shows you how to use the Second Function:

VBA Month Function

You can use the Month Function to return the month of an input date.

The syntax of the Month Function is:

  • Date_value – The date which you want to extract the month from.

The following code shows you how to use the Month Function:

VBA MonthName Function

You can use the MonthName Function to return the name of a month from an input supplied month number.

The syntax of the MonthName Function is:

MonthName(Number_of_month, [Abbreviate]) where:

  • Number_of_month – An integer value between 1 and 12.
  • Abbreviate (Optional) – Specifies whether the month name should be abbreviated. If blank the default value of False is used.

VBA TimeSerial Function

The TimeSerial Function takes an input hour, minute and second and returns a time.

The syntax of the TimeSerial Function is:

TimeSerial(Hour, Minute, Second) where:

  • Hour – An integer value between 0 and 23 that represents the hour value.
  • Minute – An integer value between 0 and 59 that represents the minute value.
  • Second – An integer value between 0 and 59 that represents the second value.

The following code shows you how to use the TimeSerial Function:

VBA TimeValue Function

The TimeValue Function returns a Time from a string representation of a date or time.

The syntax of the TimeValue Function is:

  • Time – A String representing the time.

The following code shows you how to use the TimeValue Function:

VBA Weekday Function

You can use the Weekday Function to return an integer from 1 – 7 representing a day of the week from an input date.

The syntax of the Weekday Function is:

Weekday(Date, [Firstdayofweek]) where:

  • Date – The date that you want to extract the weekday value from.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

The following code shows you how to use the Weekday Function:

VBA WeekdayName Function

You can use the WeekdayName Function to return the name of a weekday from an input supplied weekday number.

The syntax of the WeekdayName Function is:

WeekdayName(Weekday, [Abbreviate], [Firstdayoftheweek]) where:

  • Weekday – An integer value between 1 and 7.
  • Abbreviate (Optional) -Specifies whether the weekday name should be abbreviated. If blank the default value of False is used.
  • Firstdayofweek (Optional) – A constant that specifies the weekday that the function should use as the first day of the week. If blank Sunday is used as the first day of the week. Firstdayofweek can be one of the following values:

-vbSunday – uses Sunday as the first day of the week.
-vbMonday – uses Monday as the first day of the week.
-vbTuesday – uses Tuesday as the first day of the week.
-vbWednesday – uses Wednesday as the first day of the week.
-vbThursday – uses Thursday as the first day of the week.
-vbFriday – uses Friday as the first day of the week.
-vbSaturday – uses Saturday as the first day of the week.
-vbUseSystemDayOfTheWeek – uses the first day of the week that is specified by your system’s settings.

VBA Year Function

You can use the Year Function to return the year of an input date.

The syntax of the Year Function is:

  • Date_value – The date which you want to extract the year from.

The following code shows you how to use the Year Function:

Comparing Dates in VBA

You can compare dates using the >,

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.

Источник

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!

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


Home / VBA / Top VBA Functions / VBA ISDATE Function (Syntax + Example)

The VBA ISDATE function is listed under the information category of VBA functions. When you use it in a VBA code, it evaluates the supplied expression and returns TRUE if it is date else FALSE. In simple words, it can check whether the value supplied is a date or not and returns TRUE or FALSE based on that.

IsDate(Expression)

Arguments

  • Expression: An expression that you want to test if it’s a date or not.

Example

To practically understand how to use VBA ISDATE function, you need to go through the below example where we have written a vba code by using it:

Sub example_ISDATE()
Range("B1").Value = IsDate(Range("A1"))
End Sub

In the above code, we have used ISDATE to check if the value in cell A1 is a date or not and it has returned TRUE in cell B1 as a result, we have TRUE as the value in cell A1 is a date.

Like this post? Please share to your friends:
  • Excel vba if then else and or
  • Excel vba if textbox1
  • Excel vba if target column
  • Excel vba if sum of range
  • Excel vba if statements and