- Remove From My Forums
-
Question
-
Hi,
I’m trying to find a VBA code that would message the user if the their input is not in a valid date format. Please help, thanks in advance!
Answers
-
Try this code
Sub DateCheckPOC() With Sheets("POC Requests") Lastrow = .Range("H" & Rows.Count).End(xlUp).Row For RowCount = 2 To Lastrow POC = .Range("H" & RowCount) If Not IsDate(POC) Then MsgBox ("Please enter valid date in Cell : H" & RowCount & ". Example: mm/dd/yyyy") End If Next RowCount End With End Sub
jdweng
-
Marked as answer by
Tuesday, May 1, 2012 10:01 PM
-
Marked as answer by
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.
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
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
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
Open the message box in VBA now.
Code:
Sub IsDate_Example1() Dim MyDate As Date MyDate = "5.1.19" MsgBox( End Sub
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
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
Now run the code and see what we get in the message box.
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.
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
Now, run the code and see the result.
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
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.
Now, change the code as follows.
Code:
Sub IsDate_Example1() Dim MyDate As String MyDate = "05/01/2019" MsgBox IsDate(MyDate) End Sub
Instead of the dot (.) as the separator, we have entered forward-slash (/) as the separator. Now run the code and see the result.
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
We have added above the time portion of “15:26:24” in front of the date. Now, run the code and see the result.
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
На чтение 19 мин. Просмотров 24.3k.
Пьер Корнель
Угадай, если сможешь, и выбери, если посмеешь
Содержание
- Краткое руководство по VBA If Statement
- Что такое IF и зачем оно тебе?
- Тестовые данные
- Формат операторов VBA If Then
- Простой пример If Then
- Условия IF
- Использование If ElseIf
- Использование If Else
- Используя If And/If Or
- Функция IIF
- Использование Select Case
- Попробуйте это упражнение
Краткое руководство по VBA If Statement
Описание | Формат | Пример |
If Then | If [условие верно] Then [действие] End If |
If score = 100 Then Debug.Print «Отлично» End If |
If Else | If [условие верно] Then [действие] Else [действие] End If |
If score = 100 Then Debug.Print «Отлично» Else Debug.Print «Попробуй снова» End If |
If ElseIf | If [1 условие верно] Then [действие] ElseIf [2 условие верно] Then [действие] End If |
If score = 100 Then Debug.Print «Отлично» ElseIf score > 50 Then Debug.Print «Пройдено» ElseIf score <= 50 Then Debug.Print «Попробуй снова» End If |
Else и ElseIf (Else должно идти после ElseIf’s) |
If [1 условие верно] Then [действие] ElseIf [2 условие верно] Then [действие] Else [действие] End If |
If score = 100 Then Debug.Print «Отлично» ElseIf score > 50 Then Debug.Print «Пройдено» ElseIf score > 30 Then Debug.Print «Попробуй снова» Else Debug.Print «Ой» End If |
If без Endif (Только одна строка) |
If [условие верно] Then [действие] |
If value <= 0 Then value = 0 |
В следующем коде показан простой пример использования
оператора VBA If
If Sheet1.Range("A1").Value > 5 Then Debug.Print "Значение больше 5." ElseIf Sheet1.Range("A1").Value < 5 Then Debug.Print "Значение меньше 5." Else Debug.Print "Значение равно 5." End If
Что такое IF и зачем оно тебе?
Оператор VBA If используется, чтобы позволить вашему коду
делать выбор, когда он выполняется.
Вам часто захочется сделать выбор на основе данных, которые
читает ваш макрос.
Например, вы можете захотеть читать только тех учеников, у
которых оценки выше 70. Когда вы читаете каждого учащегося, вы можете
использовать инструкцию If для проверки отметок каждого учащегося.
Важным словом в последнем предложении является проверка. Оператор
If используется для проверки значения, а затем для выполнения задачи на основе
результатов этой проверки.
Тестовые данные
Мы собираемся использовать следующие тестовые данные для
примеров кода в этом посте.
Формат операторов VBA If Then
Формат оператора If Then следующий
За ключевым словом If следуют условие и ключевое слово Then
Каждый раз, когда вы используете оператор If Then, вы должны использовать соответствующий оператор End If.
Когда условие оценивается как истинное, обрабатываются все
строки между If Then и End If.
If [условие верно] Then [строки кода] [строки кода] [строки кода] End If
Чтобы сделать ваш код более читабельным, рекомендуется
делать отступы между операторами If Then и End If.
Отступ между If и End If
Отступ означает просто переместить строку кода на одну вкладку вправо. Правило большого пальца состоит в том, чтобы сделать отступ между начальным и конечным операторами, такими как:
Sub … End Sub
If Then … End If
If Then… ElseIf … Else … Endif
For … Next
Do While … Loop
Select Case … End Case
Для отступа в коде вы можете выделить строки для отступа и нажать клавишу Tab. Нажатие клавиш Shift + Tab сделает отступ кода, т.е. переместит его на одну вкладку влево.
Вы также можете использовать значки на панели инструментов Visual Basic для отступа кода.
Если вы посмотрите на примеры кода на этом сайте, вы увидите, что код имеет отступ.
Простой пример If Then
Следующий код выводит имена всех студентов с баллами более 50.
Sub ChitatOcenki() Dim i As Long ' Пройдите столбцы отметок For i = 2 To 11 ' Проверьте, больше ли баллов,чем 50 If Sheet1.Range("C" & i).Value > 50 Then ' Напечатайте имя студента в «Immediate Window» (Ctrl + G) Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value End If Next End Sub
Результаты:
- Василий Кочин
- Максим Бородин
- Дмитрий Маренин
- Олеся Клюева
- Евгений Яшин
Поэкспериментируйте с этим примером и проверьте значение или знак > и посмотрите, как изменились результаты.
Условия IF
Часть кода между ключевыми словами If и Then называется условием. Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как «>, <, <>,> =, <=, =».
Ниже приведены примеры условий:
Условие | Это верно, когда |
x < 5 | x меньше,чем 5 |
x <= 5 | x меньше, либо равен 5 |
x > 5 | x больше, чем 5 |
x >= 5 | x больше, либо равен 5 |
x = 5 | x равен 5 |
x <> 5 | x не равен 5 |
x > 5 And x < 10 | x больше, чем 5 И x меньше, чем 10 |
x = 2 Or x >10 | x равен 2 ИЛИ x больше,чем 10 |
Range(«A1») = «Иван» | Ячейка A1 содержит текст «Иван» |
Range(«A1») <> «Иван» | Ячейка A1 не содержит текст «Иван» |
Вы могли заметить x = 5, как условие. Не стоит путать с х = 5, при использовании в качестве назначения.
Когда в условии используется «=», это означает, что «левая сторона равна правой стороне».
В следующей таблице показано, как знак равенства используется
в условиях и присваиваниях.
Использование «=» | Тип | Значение |
Loop Until x = 5 | Условие | Равен ли x пяти |
Do While x = 5 | Условие | Равен ли x пяти |
If x = 5 Then | Условие | Равен ли x пяти |
For x = 1 To 5 | Присваивание | Установите значение х = 1, потом = 2 и т.д. |
x = 5 | Присваивание | Установите х до 5 |
b = 6 = 5 | Присваивание и условие |
Присвойте b результату условия 6 = 5 |
x = MyFunc(5,6) | Присваивание | Присвойте х значение, возвращаемое функцией |
Последняя запись в приведенной выше таблице показывает
оператор с двумя равными. Первый знак равенства — это присвоение, а любые
последующие знаки равенства — это условия.
Поначалу это может показаться странным, но подумайте об этом
так. Любое утверждение, начинающееся с переменной и равно, имеет следующий
формат
[переменная] [=] [оценить эту часть]
Поэтому все, что находится справа от знака равенства, оценивается и результат помещается в переменную. Посмотрите на последние три строки таблицы, как:
[x] [=] [5]
[b] [=] [6 = 5]
[x] [=] [MyFunc (5,6)]
Использование If ElseIf
Инструкция ElseIf позволяет вам выбирать из нескольких вариантов. В следующем примере мы печатаем баллы, которые находятся в диапазоне.
Sub IspElseIf() If Marks >= 85 Then Debug.Print "Высший балл" ElseIf Marks >= 75 Then Debug.Print "Отлично" End If End Sub
Важно понимать, что порядок важен. Условие If проверяется
первым.
Если это правда, то печатается «Высший балл», и оператор If заканчивается.
Если оно ложно, то код переходит к следующему ElseIf и
проверяет его состояние.
Давайте поменяемся местами If и ElseIf из последнего
примера. Код теперь выглядит так
Sub IspElseIfNeverno() ' Этот код неверен, так как ElseIf никогда не будет верным If Marks >= 75 Then Debug.Print "Отлично" ElseIf Marks >= 85 Then ' код никогда не достигнет здесь Debug.Print "Высший балл" End If End Sub
В этом случае мы сначала проверяем значение более 75. Мы никогда не будем печатать «Высший балл», потому что, если значение больше 85, это вызовет первый оператор if.
Чтобы избежать подобных проблем, мы должны использовать два
условия. Они помогают точно указать, что вы ищете, чтобы избежать путаницы.
Пример ниже показывает, как их использовать. Мы рассмотрим более многочисленные
условия в разделе ниже.
If marks >= 75 And marks < 85 Then Debug.Print "Отлично" ElseIf marks >= 85 And marks <= 100 Then Debug.Print "Высший балл" End If
Давайте расширим оригинальный код. Вы можете использовать столько операторов ElseIf, сколько захотите. Мы добавим еще несколько, чтобы учесть все наши классификации баллов.
Использование If Else
Утверждение Else используется, как ловушка для всех. Это в основном означает «если бы не было условий» или «все остальное». В предыдущем примере кода мы не включили оператор печати для метки сбоя. Мы можем добавить это, используя Else.
Sub IspElse() If Marks >= 85 Then Debug.Print "Высший балл" ElseIf Marks >= 75 Then Debug.Print "Отлично" ElseIf Marks >= 55 Then Debug.Print "Хорошо" ElseIf Marks >= 40 Then Debug.Print "Удовлетворительно" Else ' Для всех других оценок Debug.Print "Незачет" End If End Sub
Так что, если это не один из других типов, то это провал.
Давайте напишем некоторый код с помощью наших примеров
данных и распечатаем студента и его классификацию.
Sub DobClass() ' получить последнюю строку Dim startRow As Long, lastRow As Long startRow = 2 lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row Dim i As Long, Marks As Long Dim sClass As String ' Пройдите столбцы отметок For i = startRow To lastRow Marks = Sheet1.Range("C" & i).Value ' Проверьте отметки и классифицируйте соответственно If Marks >= 85 Then sClass = "Высший балл" ElseIf Marks >= 75 Then sClass = "Отлично" ElseIf Marks >= 55 Then sClass = "Хорошо" ElseIf Marks >= 40 Then sClass = "Удовлетворительно" Else ' Для всех других оценок sClass = "Незачет" End If ' Запишите класс в столбец E Sheet1.Range("E" & i).Value = sClass Next End Sub
Результаты выглядят так: в столбце E — классификация баллов
Используя If And/If Or
В выражении If может быть несколько условий. Ключевые слова VBA And и Or позволяют использовать несколько условий.
Эти слова работают так же, как вы используете их на
английском языке.
Давайте снова посмотрим на наши примеры данных. Теперь мы
хотим напечатать всех студентов, которые набрали от 50 до 80 баллов.
Мы используем Аnd, чтобы добавить дополнительное условие. Код гласит: если оценка больше или равна 50 и меньше 75, напечатайте имя студента.
Sub ProverkaStrokiOcenok() Dim i As Long, marks As Long For i = 2 To 11 ' Хранить оценки для текущего студента marks = Sheet1.Range("C" & i).Value ' Проверьте, если отметки больше 50 и меньше 75 If marks >= 50 And marks < 80 Then ' Напечатайте имя и фамилию в Immediate window (Ctrl+G) Debug.Print Sheet1.Range("A" & i).Value & Sheet1.Range("B" & i).Value End If Next End Sub
Вывести имя и фамилию в результаты:
- Дмитрий Маренин
- Олеся Клюева
- Евгений Яшин
В нашем следующем примере мы хотим знать, кто из студентов сдавал историю или геометрию. Таким образом, в данном случае мы говорим, изучал ли студент «История» ИЛИ изучал ли он «Геометрия» (Ctrl+G).
Sub ChitatObektOcenki() Dim i As Long, marks As Long ' Пройдите столбцы отметок For i = 2 To 11 marks = Sheet1.Range("D" & i).Value ' Проверьте, если отметки больше 50 и меньше 80 If marks = "История" Or marks = "Геометрия" Then ' Напечатайте имя и фамилию в Immediate window (Ctrl+G) Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value End If Next End Sub
Результаты:
- Василий Кочин
- Александр Грохотов
- Дмитрий Маренин
- Николай Куликов
- Олеся Клюева
- Наталия Теплых
- Дмитрий Андреев
Использование нескольких таких условий часто является
источником ошибок. Эмпирическое правило, которое нужно помнить, должно быть
максимально простым.
Использование IF AND
And работает следующим образом:
Условие 1 | Условие 2 | Результат |
ИСТИНА | ИСТИНА | ИСТИНА |
ИСТИНА | ЛОЖЬ | ЛОЖЬ |
ЛОЖЬ | ИСТИНА | ЛОЖЬ |
ЛОЖЬ | ЛОЖЬ | ЛОЖЬ |
Что вы заметите, так это то, что And верно только тогда, когда все условия выполняются.
Использование IF OR
Ключевое слово OR работает следующим образом
Условие 1 | Условие 2 | Результат |
ИСТИНА | ИСТИНА | ИСТИНА |
ИСТИНА | ЛОЖЬ | ИСТИНА |
ЛОЖЬ | ИСТИНА | ИСТИНА |
ЛОЖЬ | ЛОЖЬ | ЛОЖЬ |
Что вы заметите, так это то, что OR ложно, только когда все условия ложны.
Смешивание And и Or может затруднить чтение кода и привести к ошибкам. Использование скобок может сделать условия более понятными.
Sub OrSAnd() Dim subject As String, marks As Long subject = "История" marks = 5 If (subject = "Геометрия" Or subject = "История") And marks >= 6 Then Debug.Print "ИСТИНА" Else Debug.Print "ЛОЖЬ" End If End Sub
Использование IF NOT
Также есть оператор NOT. Он возвращает противоположный результат условия.
Условие | Результат |
ИСТИНА | ЛОЖЬ |
ЛОЖЬ | ИСТИНА |
Следующие две строки кода эквивалентны.
If marks < 40 Then If Not marks >= 40 Then
так же, как и
If True Then If Not False Then
и
If False Then If Not True Then
Помещение условия в круглые скобки облегчает чтение кода
If Not (marks >= 40) Then
Распространенное использование Not — при проверке, был ли установлен объект. Возьмите Worksheet для примера. Здесь мы объявляем рабочий лист.
Dim mySheet As Worksheet ' Некоторый код здесь
Мы хотим проверить действительность mySheet перед его использованием. Мы можем проверить, если это Nothing.
If mySheet Is Nothing Then
Нет способа проверить, является ли это чем-то, поскольку есть много разных способов, которым это может быть что-то. Поэтому мы используем NOT с Nothing.
If Not mySheet Is Nothing Then
Если вы находите это немного запутанным, вы можете использовать круглые скобки, как здесь
If Not (mySheet Is Nothing) Then
Функция IIF
VBA имеет функцию, аналогичную функции Excel If. В Excel вы часто используете функцию If следующим образом:
= ЕСЛИ (F2 =»»,»», F1 / F2)
Формат
= If (условие, действие, если ИСТИНА, действие, если ЛОЖЬ).
VBA имеет функцию IIf, которая работает так же. Давайте посмотрим на примере. В следующем коде мы используем IIf для проверки значения переменной val. Если значение больше 10, мы печатаем ИСТИНА, в противном случае мы печатаем ЛОЖЬ.
Sub ProveritVal() Dim result As Boolean Dim val As Long ' Печатает ИСТИНА val = 11 result = IIf(val > 10, ИСТИНА, ЛОЖЬ) Debug.Print result ' печатает ЛОЖЬ val = 5 result = IIf(val > 10, ИСТИНА, ЛОЖЬ) Debug.Print result End Sub
В нашем следующем примере мы хотим распечатать «Удовлетворитеьно» или «Незачет» рядом с каждым студентом в зависимости от их баллов. В первом фрагменте кода мы будем использовать обычный оператор VBA If, чтобы сделать это.
Sub ProveritDiapazonOcenok() Dim i As Long, marks As Long For i = 2 To 11 ' Хранить оценки для текущего студента marks = Sheet1.Range("C" & i).Value ' Проверьте, прошел ли студент или нет If marks >= 40 Then ' Запишите имена для столбца F Sheet1.Range("E" & i) = "Удовлетворительно" Else Sheet1.Range("E" & i) = "Незачет" End If Next End Sub
В следующем фрагменте кода мы будем использовать функцию IIf. Код здесь намного аккуратнее.
Sub ProveritDiapazonOcenok () Dim i As Long, marks As Long For i = 2 To 11 ' Хранить оценки для текущего студента marks = Sheet1.Range("C" & i) ' Проверьте, прошел ли студент или нет Sheet1.Range("E" & i).Value = IIf(marks >= 40,"Удовлетворительно","Незачет") Next End Sub
Функция IIf очень полезна для простых случаев, когда вы имеете дело с двумя возможными вариантами.
Использование Nested IIf
Вы также можете вкладывать IIf-операторы, как в Excel. Это означает использование результата одного IIf с другим. Давайте добавим еще один тип результата в наши предыдущие примеры. Теперь мы хотим напечатать «Отлично», «Удовлетворительно» или «Незачетт» для каждого студента.
Используя обычный VBA, мы сделали бы это так
Sub ProveritRezultatiTip2() Dim i As Long, marks As Long For i = 2 To 11 ' Хранить оценки для текущего студента marks = Sheet1.Range("C" & i).Value If marks >= 75 Then Sheet1.Range("E" & i).Value = "Отлично" ElseIf marks >= 40 Then ' Запишите имена для столбца F Sheet1.Range("E" & i).Value = "Удовлетворительно" Else Sheet1.Range("E" & i).Value = "Незачет" End If Next End Sub
Используя вложенные IIfs, мы могли бы сделать это так
Sub IspNestedIIF() Dim i As Long, marks As Long, result As String For i = 2 To 11 marks = Sheet1.Range("C" & i).Value result = IIf(marks >= 55,"Хорошо",IIf(marks >= 40,"Удовлетворительно","Незачет")) Sheet1.Range("E" & i).Value = result Next End Sub
Использование вложенного IIf хорошо в простых случаях, подобных этому. Код прост для чтения и, следовательно, вряд ли вызовет ошибки.
Чего нужно остерегаться
Важно понимать, что функция IIf всегда оценивает как
Истинную, так и Ложную части выражения независимо от условия.
В следующем примере мы хотим разделить по баллам, когда он не равен нулю. Если он равен нулю, мы хотим вернуть ноль.
marks = 0 total = IIf(marks = 0, 0, 60 / marks)
Однако, когда отметки равны нулю, код выдаст ошибку «Делить на ноль». Это потому, что он оценивает как Истинные, так и Ложные утверждения. Здесь ложное утверждение, т.е. (60 / Marks), оценивается как ошибка, потому что отметки равны нулю.
Если мы используем нормальный оператор IF, он будет
запускать только соответствующую строку.
marks = 0 If marks = 0 Then 'Выполняет эту строку только когда отметки равны нулю total = 0 Else 'Выполняет только эту строку, когда отметки не равны нулю total = 60 / marks End If
Это также означает, что если у вас есть функции для ИСТИНА и ЛОЖЬ, то обе будут выполнены. Таким образом, IIF будет запускать обе функции, даже если он использует только одно возвращаемое значение. Например:
' Обе функции будут выполняться каждый раз total = IIf(marks = 0, Func1, Func2)
IF против IIf
Так что лучше?
В этом случае вы можете видеть, что IIf короче для написания и аккуратнее. Однако если условия усложняются, вам лучше использовать обычное выражение If. Недостатком IIf является то, что он недостаточно известен, поэтому другие пользователи могут не понимать его так же, как и код, написанный с помощью обычного оператора if.
Кроме того, как мы обсуждали в последнем разделе, IIF всегда оценивает части ИСТИНА и ЛОЖЬ, поэтому, если вы имеете дело с большим количеством данных, оператор IF будет быстрее.
Мое эмпирическое правило заключается в том, чтобы
использовать IIf, когда
он будет прост для чтения и не требует вызовов функций. Для более сложных
случаев используйте обычный оператор If.
Использование Select Case
Оператор Select Case
— это альтернативный способ написания статистики If с большим количеством ElseIf. Этот тип операторов
вы найдете в большинстве популярных языков программирования, где он называется
оператором Switch. Например,
Java, C #, C ++ и Javascript
имеют оператор switch.
Формат
Select Case [переменная] Case [условие 1] Case [условие 2] Case [условие n] Case Else End Select
Давайте возьмем наш пример DobClass сверху и перепишем его с помощью оператора Select Case.
Sub DobavitClass() ' получить последнюю строку Dim startRow As Long, lastRow As Long startRow = 2 lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row Dim i As Long, Marks As Long Dim sClass As String ' Пройдите столбцы отметок For i = startRow To lastRow Marks = Sheet1.Range("C" & i).Value ' Проверьте отметки и классифицируйте соответственно If Marks >= 85 Then sClass = "Высший балл" ElseIf Marks >= 75 Then sClass = "Отлично" ElseIf Marks >= 55 Then sClass = "Хорошо" ElseIf Marks >= 40 Then sClass = "Удовлетворительно" Else ' Для всех других оценок sClass = "Незачет" End If ' Запишите класс в столбец E Sheet1.Range("E" & i).Value = sClass Next End Sub
Ниже приведен тот же код с использованием оператора Select Case. Главное, что вы заметите, это то, что мы используем “Case 85 to 100” rather than “marks >=85 And marks <=100”. , а не “marks >=85 And marks <=100”.
Sub DobavitClassSSelect() ' получить первую и последнюю строки Dim firstRow As Long, lastRow As Long firstRow = 2 lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row Dim i As Long, marks As Long Dim sClass As String ' Пройдите столбцы отметок For i = firstRow To lastRow marks = Sheet1.Range("C" & i).Value ' Проверьте отметки и классифицируйте соответственно Select Case marks Case 85 To 100 sClass = "Высший балл" Case 75 To 84 sClass = "Отлично" Case 55 To 74 sClass = "Хорошо" Case 40 To 54 sClass = "Удовлетворительно" Case Else ' Для всех других оценок sClass = "Незачет" End Select ' Запишите класс в столбец E Sheet1.Range("E" & i).Value = sClass Next End Sub
Использование Case Is
Вы можете переписать оператор select в том же формате, что и оригинальный ElseIf. Вы можете использовать Is с Case.
Select Case marks Case Is >= 85 sClass = "Высший балл" Case Is >= 75 sClass = "Отлично" Case Is >= 55 sClass = "Хорошо" Case Is >= 40 sClass = "Удовлетворительно" Case Else ' Для всех других оценок sClass = "Незачет" End Select
Вы можете использовать Is для проверки нескольких значений.
В следующем коде мы проверяем, равны ли оценки 5, 7 или 9.
Sub TestNeskZnach() Dim marks As Long marks = 7 Select Case marks Case Is = 5, 7, 9 Debug.Print True Case Else Debug.Print False End Select End Sub
Попробуйте это упражнение
В этой статье много рассказывали о выражении If. Хороший способ помочь вам понять — это попытаться написать код, используя темы, которые мы рассмотрели. В следующем упражнении используются тестовые данные из этой статьи. Ответ на упражнение ниже.
Мы будем использовать ячейку G1, чтобы написать имя
субъекта.
В колонках от H до L запишите всех студентов, которые имеют оценки по этому предмету. Мы хотим классифицировать их результат как успешный или неудачный. Оценка ниже 40 — неудача, оценка 40 или выше — Зачет.
Колонка H: Имя
Колонка I: Фамилия
Колонка J: Баллы
Колонка H: Предмет
Столбец I: Тип результата — Зачет или Незачет
Если ячейка G1 содержит «Геометрия», то ваш результат должен выглядеть следующим образом:
Ответ на упражнение
Следующий код показывает, как выполнить вышеупомянутое упражнение.
Примечание: есть много способов выполнить задачу, поэтому не расстраивайтесь, если ваш код отличается.
Sub ZapisatRezultat() ' Получить тему Dim subject As String subject = Sheet1.Range("G1").Value If subject = "" Then Exit Sub End If ' Получить первый и последний ряд Dim firstRow As Long, lastRow As Long firstRow = 2 lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row ' Очистить любой существующий вывод Sheet1.Range("H:L").ClearContents ' Отслеживать выходной ряд Dim outRow As Long outRow = 1 Dim i As Long, marks As Long, rowSubject As String ' Прочитать данные For i = firstRow To lastRow marks = Sheet1.Range("C" & i).Value rowSubject = Sheet1.Range("D" & i).Value If rowSubject = subject Then ' Запишите данные студента, если предмет Геометрия Sheet1.Range("A" & i & ":" & "D" & i).Copy Sheet1.Range("H" & outRow).PasteSpecial xlPasteValues ' Запишите Зачет или Незачет If marks < 40 Then Sheet1.Range("L" & outRow).Value = "Незачет" ElseIf marks >= 40 Then Sheet1.Range("L" & outRow).Value = "Зачет" End If ' Переместить вывод в следующую строку outRow = outRow + 1 End If Next i End Sub
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:
VBA Code:
Sub ConvertToDate()
Dim cell As Range, strCell As String
Application.ScreenUpdating = False
For Each cell In Range("AB2:AB" & Cells(Rows.Count, 28).End(xlUp).Row)
With cell
strCell = .Value
.Value = WorksheetFunction.Substitute(strCell, ".", "/")
If IsDate(.Value) = False Then .Value = .Value & " is not a date."
End With
Next cell
Columns(28).AutoFit
Application.ScreenUpdating = True
End Sub
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
Excel provides you several options for formatting dates. In addition to the several built-in date formats that exist, you can create custom date formats.
Even though the process of manually applying a date format isn’t very complicated, there are some circumstances in which you may want to create macros that format dates. This may the case if, for example:
- You use a particular date format constantly and want to be able to apply such a format without having to do everything manually; or
- You frequently format cells or cell ranges in a particular way, and the formatting rules you apply include date formats.
Regardless of your situation, if you’re interested in understanding how you can use Visual Basic for Applications for purposes of formatting dates, you’ve found the right place.
When working in Visual Basic for Applications, there are a few different properties and functions you can use for purposes of formatting a date. The following 3 are commonly used:
- The Format VBA function.
- The Range.NumberFormatLocal property.
- The Range.NumberFormat property.
This particular Excel tutorial focuses on the last item of the list above (the Range.NumberFormat property). I may cover the Format function and Range.NumberFormatLocal property in future blog posts. If you want to be informed whenever I publish new content in Power Spreadsheets, please make sure to register for our Newsletter by entering your email address below.
In addition to explaining the Range.NumberFormat property, I explain the different date format codes you can use and present 25 date formatting examples using VBA.
You can use the following detailed table of contents to navigate to the section of this tutorial that interests you the most.
Before I introduce the NumberFormat property in more detail, let’s start by taking a look at the sample file that accompanies this Excel tutorial:
Format Dates Using Excel VBA: Example
For purpose of this Excel tutorial, I use an Excel workbook that contains the full match schedule of the 2014 Brazil World Cup.
This Excel VBA Date Format Tutorial is accompanied by an Excel workbook containing the data and some versions of the macros I explain below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Notice how the first column of the table contains dates:
These are the dates that I format throughout this tutorial.
However, since the focus of this macro is in formatting dates using VBA, we need a Sub procedure. The following image shows the basic structure of the macro (called “Format_Dates”) that I use to format these dates.
The macro has a single statement:
Selection.NumberFormat = “m/d/yy;@”
Therefore, before I start showing examples of how you can format dates using VBA, let’s analyze this statement. For these purposes, you simply need to understand…
The Range.NumberFormat Property And How To Format An Excel Date Using VBA
As mentioned at the beginning of this Excel tutorial, you can generally use the Range.NumberFormat property to format dates.
The Range.NumberFormat property sets a Variant value. This value represents the number format code of the relevant Range object. For these purposes, the Range object is generally a single cell or a range of cells.
Strictly speaking, in addition to setting the NumberFormat property value, you can also return the property’s current setting. As explained by Excel authority John Walkenbach in Excel VBA Programming for Dummies, the NumberFormat property is a read-write property.
However, if you’re reading this Excel tutorial, you likely want to modify the property, not read it. Therefore, this guide focuses on how to change the NumberFormat property, not how to read it.
You can, however, easily examine the number format of a cell or range of cells. I explain how you can read a property value in this tutorial. In such cases, if (i) you select a range of cells and (ii) all the cells don’t share the same format, the Range.NumberFormat property returns Null.
NumberFormat is just one of the many (almost 100 by my count) properties of the Range object. As explained in Excel Macros for Dummies, once you’ve selected a range of cells (as the sample Format_Dates macro does), “you can use any of the Range properties to manipulate the cells”.
This Excel tutorial is quite specific. The only property of the Range object that I cover in this blog post is NumberFormat. In fact, I only explain (in high detail) one of the applications of the NumberFormat property: to format dates with VBA.
I may cover other properties of the Range object, or other applications of the NumberFormat property, in future tutorials. If you want to receive an email whenever I publish new material in Power Spreadsheets, please make sure to subscribe to our Newsletter by entering your email address below:
Syntax Of The Range.NumberFormat Property
The syntax of the Range.NumberFormat property is relatively simple:
expression.NumberFormat
In this case, “expression” stands for the Range object, or a variable that represents this object.
The sample Format_Dates macro shown above uses the Application.Selection property, which returns whichever object is selected. Generally, you can use the sample Format_Dates macro framework whenever the selection is a range of cells. Therefore, the sample macro uses the following version of the syntax above:
Selection.NumberFormat
You can use another expression instead of Selection. What matters, as I mention above, is that the expression stands for a Range object.
Whenever you want to modify the value of a property, you must do the following:
- #1: Determine whether the property you’re working with uses arguments and, if that’s the case, determine what is the argument you want to use. These arguments are the ones that specify the value that the property takes.
- #2: Use an equal sign to separate the property name from the property value.
As shown in the examples throughout this tutorial, if you’re implementing the NumberFormat property using the framework structure of the sample Format_Dates macro, argument values are generally surrounded by double quotes (” “).
Therefore, if you’re setting the NumberFormat property value, you can use the following syntax:
expression.NumberFormat = “argument_value”
In other words, in order to change the current setting of the NumberFormat property, you use a statement including the following 3 items:
- Item #1: A reference to the NumberFormat property.
- Item #2: The equal sign (=).
- Item #3: The new value of the NumberFormat property, surrounded by double quotes (” “).
As I explain above, the Range.NumberFormat property determines the number format code of a Range object. Therefore, in order to be able to format a date using VBA, you must understand…
Date Format Codes: The Arguments Of The Range.NumberFormat Property
As explained at the Microsoft Dev Center:
The format code is the same string as the Format Codes option in the Format Cells dialog box.
This is quite a mouthful, so let’s break down the statement and process into different parts to understand how you can know which format code you want to apply. More precisely, you can find the string that represents a particular format code in the Format Cells dialog box in the following 5 easy steps.
This process is, mostly, useful if you don’t know the format code you want to apply. Generally, as you become more familiar with number format codes, you’ll be able to create macros that format dates without having to go through this every time. For these purposes, refer to the introduction to date format codes below.
Step #1: Go To The Number Tab Of The Format Cells Dialog Box
You can get to the Format Cells dialog box using any of the following methods:
- Method #1: Click on the dialog box launcher at the bottom-right corner of the Number command group of the Home Ribbon tab.
- Method #2: Go to the Home tab of the Ribbon, expand the Number Format drop-down list and select More Number Formats.
- Method #3: Use the “Ctrl + 1” keyboard shortcut.
Regardless of which of the methods above you use, Excel displays the Format Cells dialog box.
If you use method #1 or #2 above, Excel displays the Number tab, as in the image above. This is the one you need in order to find the date format codes.
However, if you use method #3 (keyboard shortcut), Excel may show you a tab other than the Number tab (as shown above). In such a case, simply go to the Number tab.
Step #2: Select The Date Category
Since you’re interested in date format codes, choose “Date” in the Category list box on the left side of the Format Cells dialog box.
Step #3: Choose The Date Format Type Whose Format Code You Want
Once you’ve selected the Date category, Excel displays the built-in date format types inside the Type box on the right side of the Format Cells dialog box. This allows you to select from several different date format types.
For example, in the image above, I select the option “14-Mar-12”:
Step #4: Select The Custom Category
Once you’ve selected the date format type you’re interested in, click on “Custom” within the Category list box on the right side of the Format Cells dialog.
Step #5: Get The Date Format Code
Once you’ve completed the 4 steps above, Excel displays the date format code that corresponds to the date format type you selected in step #3 above. This format code is shown in the Type box that appears on the upper-right section of the Format Cells dialog box.
The date format code shown in the example above, is “[$-en-US]d-mmm-yy;@”. This format code corresponds to the option “14-Mar-12” with the English (United States) locale that I selected in step #3.
Once you have this date format code, you can go back to you VBA code and use this as the argument for the Range.NumberFormat property.
To see how this works in practice, let’s go back to the World Cup calendar that I introduce above. If you want to apply the format shown above, the VBA code looks as follows:
As I show below, you can achieve the same date formatting effect without the first part of the date format code which makes reference to the locale settings. That means you can delete “[$-en-US]”. However, for the moment, I leave it in.
For purposes of this example, I modify the format of the dates that appear in the sample table. Let’s assume that, before applying this new version of the Format_Dates macro, all of the dates have the long date format, as shown in the following screenshot:
Before executing the Format_Dates macro, I select the cell that I want to format. In this case, I choose the date in the first row of the table. This corresponds to June 12 of 2014, which is the date of the match between Brazil and Croatia.
Once I execute the version above of the Format_Dates macro, the date format changes to the following:
The 5-step method to find date format codes described above can be useful in some situations.
However, Excel date format codes follow some general rules. If you know them, you don’t have to go through the whole process described above every single time you want to create a macro that formats dates.
Let’s take a look at these general rules and some additional examples:
Date Format Codes In Excel And VBA: General Guidelines
The date format codes that you can use to format a date using VBA appear in the table below. As shown in the following sections, you can use these codes to create different types of date formats to use in your VBA code.
Format Code Applies To | Format Code | Description | How It Looks In Practice |
---|---|---|---|
Month | m | Month is displayed as number.
It doesn’t include a leading 0. |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 |
Month | mm | Displays month as a number.
If the month is between January (month 1) and September (month 9), it includes a leading 0. |
01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12 |
Month | mmm | Month name is abbreviated. | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
Month | mmmm | Full name of month is displayed | January, February, March, April, May, June, July, August, September, October, November, December |
Month | mmmmm | Only the first letter of the month name is displayed | J, F, M, A, M, J, J, A, S, O, N, D |
Day (Number) | d | The day number is displayed without a leading 0. | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 |
Day (Number) | dd | The day number is displayed.
For days between 1 and 9, a leading 0 is displayed. |
01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 |
Day (Weekday) | ddd | The weekday is abbreviated | Mon, Tue, Wed, Thu, Fri, Sat, Sun |
Day (Weekday) | dddd | The full weekday name is displayed | Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday |
Year | yy | The last 2 digits of the year are displayed | 00 to 99 |
Year | yyyy | All of the four digits of the year are displayed | 1900 to 9999 |
Note, however, that the Format function (which I mention at the beginning of this Excel tutorial) supports slightly different date format codes from those appear in this table.
The following sections show examples of how all of these different options can be applied to format dates using VBA. For each situation, I show both of the following:
- The VBA code of the sample Format_Dates macro.
- The resulting format in one of the dates within the sample table that contains the 2014 Brazil World Cup schedule.
Let’s start taking a look at each of these:
Format Date Using VBA: Display A Single Item Of The Date
You can have Excel display just one of the items of a date, regardless of whether it’s the month, the day or the year. To do this, the argument of the Range.NumberFormat property must only include the format code of the relevant item.
Let’s take a look at the different date formats you can obtain by including a single item, and how does the corresponding VBA code looks like:
Format A Date To Display Only The Month Using VBA
You can display a month using any of the following 5 options:
Option #1: Display The Month As A Number (Without Leading 0)
You can format a date in a way that:
- Only the month is displayed; and
- The month is displayed as a number without a leading 0.
In this case, the format code that you use as argument for the NumberFormat property is “m”. The image shows the version of the sample Format_Dates macro that does this:
Let’s go back to the sample table with the schedule of the 2014 World Cup. I select the second date, which is June 13 of 2014 and corresponds to the match between Mexico and Cameroon.
The following image shows the results after the date is formatted by the Format_Dates macro. Notice how only the month number (6, corresponding to June) appears. Notice, also, that the value in the Formula Bar continues to be the same. The only thing that changes is the format of the date displayed in the cell itself.
Option #2: Display The Month As A Number (With Leading 0)
This option is similar to the one above. More particularly:
- Only the month is displayed; and
- The month is displayed as a number.
However, in this particular case, the month is displayed with a leading 0. In other words, if the relevant month is between January (month 01) and September (month 09), a leading 0 is added.
For these purposes, the VBA code behind the Format_Dates macro looks as follows:
This particular macro is applied to the third date in the 2014 World Cup schedule. The date is June 13 of 2014. The teams playing are Spain and Netherlands.
Once the Format_Dates macro is applied, the date looks as follows in the cell (where the format changes) and the Formula Bar (where the value remains the same):
Option #3: Display The Month As A 3-Letter Abbreviation
If you choose to implement this option, the month name is displayed as a 3-letter abbreviation. In order to achieve this, the VBA code of the Format_Dates macro is as follows:
Let’s continue with the same process of applying the new date formats to the match dates of the 2014 Brazil World Cup. In this case, the relevant date is June 13 of 2014. The match played is between Chile and Australia.
The following image shows how the cell looks like after the new format is applied. As in the previous cases, the value of the date itself (as shown in the Formula Bar), doesn’t change.
Option #4: Display The Full Name Of The Month
If you want to display the full name of the month that corresponds to a date (not just its abbreviation), the following version of the Format_Dates macro is of help:
In order to apply this format to a date in the sample 2014 Brazil World Cup schedule, I select the corresponding cell. In this case, the date is June 14 of 2014 and corresponds to the match between Colombia and Greece.
The results of applying the new version of the Format_Dates macro are shown in the following screenshot:
Option #5: Display The First Letter Of The Month
The fifth way in which you can display just the month when formatting a date using VBA is to display (only) the first letter of the relevant month. In this case, the Format_Dates macro looks as follows:
This macro is applied to the date June 14 of 2014. This date corresponds to the match between Uruguay and Costa Rica.
The results of executing the new macro are shown in the following image:
Format A Date To Display Only The Day Number Using VBA
Just as you can use VBA to format a date in a way that only the month is displayed, you can do the same for the day. In other words, you can use Visual Basic for Applications to format a date and have Excel display only the day.
The following 2 sections show how you can modify the sample Format_Dates macro so that only the day (number) is displayed when the date is formatted.
Option #1: Display The Day Number Without Leading 0
If you want Excel to display the day number without a leading 0 while using VBA, you can use the following version of the sample Format_Dates macro:
The date to which this macro is applied in the sample workbook is June 14 of 2014. In this case, the relevant match is that between England and Italy.
The results of applying the Format_Dates macro are shown in the following image:
Option #2: Display The Day Number With Leading 0
You can format dates in such a way that Excel adds a leading 0 whenever the day is only 1 digit long (1 to 9). The following version of the Format_Dates macro achieves this:
If I continue going down the 2014 Brazil World Cup match schedule (as until now), this version of the Format_Dates macro would be applied to the date June 14 of 2014. This date corresponds to the match between Ivory Coast and Japan.
However, since this the day (14) doesn’t require a leading 0, the result of applying the new version of the Format_Dates macro would be the same as that obtained above for the date of the match between England and Italy.
To see how this date format works like whenever the corresponding day is only one digit long, I go further down the sample table to one of the matches played at the beginning of July of 2014. More precisely, I apply the current version of the Format_Dates macro to the date July 1 of 2014. The match to which this date corresponds to is that played between Argentina and Switzerland.
The following image shows the results of applying the Format_Dates macro to this date. Notice how, now, Excel adds a leading 0 to the day number in the cell.
Format A Date To Display Only The Weekday Using VBA
The previous section shows how you can use VBA to format a date in such a way that only the day number is displayed. You can also format a date in such a way that only the weekday is displayed.
The following 2 sections show 2 ways in which you can implement this date format by using VBA.
Option #1: Display The Weekday As A 3-Letter Abbreviation
The first way in which you can format a date to display the weekday allows you to have that weekday shown as a 3-letter abbreviation. The following version of the Format_Dates macro achieves this:
Let’s go back to the match between Ivory Coast and Japan to which I make reference above and apply this new date format. The date of this match is June 14 of 2014.
After executing the Format_Dates macro, the date looks as follows:
Option #2: Display The Full Weekday
The second way in which you can format a date to display the weekday using VBA makes Excel show the full name of the weekday. The following version of the sample Format_Dates macro formats a date in such a way:
Let’s execute this macro for purposes of formatting the date of the match between Switzerland and Ecuador in the 2014 Brazil World Cup match schedule. This date, as shown in the image below, is June 15 of 2014.
Running the Format_Dates macro while this particular cell is active causes the following change in the date format:
Format A Date To Display Only The Year Using VBA
So far, you have seen how you can format a date using VBA for purposes of displaying only the (i) month, (ii) day number or (iii) weekday. In this section, I show you how to format a date using VBA to display only the year.
Let’s take a look at the 2 options you have for these purposes:
Option #1: Display The Last 2 Digits Of The Year
The first way in which you can format a date to display only the year results in Excel displaying only the last 2 digits of the relevant year. To achieve this date format, you can use the following version of the Format_Dates macro:
This date format is to applied to the date June 15 of 2014. This corresponds to the World Cup match between France and Honduras.
The following image shows the results of executing the sample Format_Dates macro while this cell is active:
Option #2: Display The Full Year
The second way in which you can format a date to display only the year results in Excel showing the full year. If you want to format a date in such a way using VBA, the following version of the Format_Dates macro achieves this result:
I apply this date format to the date of the match between Argentina and Bosnia and Herzegovina. This is June 15 of 2014.
Once the Format_Dates macro is executed, the results are as shown in the following screenshot:
Format Date Using VBA: Display Several Items Of The Date
The examples in the section above explain different ways in which you can format a date using VBA to display a single item (month, day or year) of that particular date.
Having the ability to format a date in such a way that only a single item is displayed is helpful in certain scenarios. Additionally, once you know the format codes that apply to each of the individual items of a date, you can easily start combining them for purposes of creating more complex and advanced date formats.
In any case, in a lot of cases, you’ll need to format dates in such a way that more than 1 element is displayed. In the following sections, I go through some date formats that result in Excel displaying more than 1 item of the relevant date.
Even though I don’t cover every single date format that you can possibly implement, these examples give you an idea of the possibilities you have at your disposal and how you can implement them in your VBA code.
All of the sections below follow the same form and show 2 things:
- The version of the Format_Dates macro that is applied.
- The result of executing that macro for purposes of formatting 1 of the dates of a match in the sample workbook that accompanies this blog post.
Format Date Using VBA: Display m/d/yyyy
The following version of the Format_Dates macro formats a date in the form m/d/yyyy.
The following image shows the result of applying this format to the date June 16 of 2014. This date corresponds to the match between Germany and Portugal.
Format Date Using VBA: Display m/d
To display a date in the form m/d, you can use the following macro:
When this macro is executed and the cell with the date of the match between Iran and Nigeria (June 16 of 2014) is selected, the formatted date looks as follows:
Format Date Using VBA: Display m/d/yy
The following macro formats a date so that it’s displayed in the form m/d/yy:
The result of applying this format, using the version of the Format_Dates macro above, to the date of June 16 of 2014 (for the match between Ghana and the USA) is shown below:
Format Date Using VBA: Display mm/dd/yy
You can format a date so that it’s displayed in the form mm/dd/yy by using the following version of the Format_Dates macro:
When this date format applied to the date of the World Cup match between Belgium and Algeria (June 17 of 2014), the result is as shown in the following image:
Format Date Using VBA: Display d-mmm
The following version of the Format_Dates macro makes Excel display the date in the form d-mmm:
The results of executing this macro while the date of the World Cup match between Brazil and Mexico is selected (June 17 of 2014) are shown in the next image:
Format Date Using VBA: Display d-mmm-yy
The next version of the Format_Dates macro makes Excel display dates using the form d-mmm-yy:
If I choose the cell that shows the date of the match between Russia and Korea (June 17 of 2014) prior to executing this version of the Format_Dates macro, the resulting date format is as follows:
Format Date Using VBA: Display dd-mmm-yy
To apply the format dd-mmm-yy to a particular date, you can use the following version of the sample Format_Dates macro:
The following screenshot shows the results of applying this version of the Format_Dates macro to the date in which Australia played against the Netherlands in the 2014 Brazil World Cup (June 18 of 2014):
Notice that, in this particular case, the resulting date format is exactly the same as that of the date of the match between Russia and Korea which is immediately above (and is used as an example in the previous section). To understand why this is the case, let’s take a look at the date format codes used in each case:
- Russia vs. Korea (June 17 of 2014) uses the date format code d-mmm-yy.
- Australia vs. Netherlands (June 18 of 2014) has the date format code dd-mmm-yy.
Notice that the only difference between both format codes is in the way the day is represented. In the first case, the format code uses “d”, which displays the day number without a leading 0. In the second case, the format code is “dd”, which adds a leading 0 whenever the day number has a single digit (between 1 and 9).
In this particular situation, the day numbers of both dates (17 and 18) have 2 digits. Therefore, the format code “dd” doesn’t add a leading 0 to the day number. The result is that shown above:
Both format codes (d-mmm-yy and dd-mmm-yy) result in the same date format when the number of digits of the day is 2 (between 10 and 31).
Let’s go further down the match schedule of the 2014 Brazil World Cup to see how the format code “dd-mmm-yy” adds a leading 0 when applied to a date in which the day number has a single digit:
The image below shows this. In this particular case, the Format_Dates macro is applied to the date July 1 of 2014, when Belgium played against the USA. Notice, especially, the leading 0 in the day number (01 instead of 1).
Format Date Using VBA: mmm-yy
The following version of the Format_Dates macro allows you to format a date using the form mmm-yy:
The resulting date format when this version of the Format_Date macro is executed is as shown in the image below. The formatted date is June 18 of 2014, corresponding to the match between Spain and Chile.
Format Date Using VBA: mmmm-yy
Continuing with date formats that only display the month and year, the following version of the Format_Dates macro applies the format code mmmm-yy:
The results of executing the macro on the date June 18 of 2014 are shown in the image below. In this case, the date corresponds to the World Cup match between Cameroon and Croatia.
Format Date Using VBA: mmmm d, yyyy
The following version of the sample Format_Dates macro formats dates so that they’re displayed using the form mmmm d, yyyy.
The next image shows the results of executing this macro while a cell with the date June 19 of 2014 is active. This date corresponds to the world cup match between Colombia and Ivory Coast.
Format Date Using VBA: mmmmm-yy
The following version of the sample Format_Dates macro makes Excel display dates using the format mmmmm-yy.
To see how a date looks like when formatted by this version of the Format_Dates macro, let’s go back to the 2014 Brazil World Cup match schedule. The following screenshot shows how the date June 19 of 2014 (for the match between Uruguay and England) looks like after this macro is executed:
Format Date Using VBA: d-mmm-yyyy
Further above, I show versions of the Format_Dates macro that use the format codes d-mmm-yy and dd-mmm-yy. The version of this macro displayed in the image below results in a similar date format. The main difference between this version and those displayed above is that the version below displays the 4 digits of the year.
I execute this macro while the cell with the date of the World Cup match between Japan and Greece (June 19 of 2014) is selected. The resulting date format is displayed in the image below:
Format Date Using VBA: dddd, mmmm dd, yyyy
The following version of the sample Format_Dates macro makes Excel display dates using the default long date format under the English (United States) locale settings.
To see how this looks in practice, check out the following image. This screenshot shows the date of the match between Italy and Costa Rica (June 20 of 2014) after the Format_Dates macro has been executed:
So far, this Excel tutorial includes 24 different examples of how you can use Visual Basic for Applications to format dates. The date formats introduced in the previous sections are relatively straightforward.
These basic date formats include several of the most commonly used date formats in American English. You can also use them as a basis to create other date formatting macros for less common date formats.
These basic date formats are, however, not the only ones you can apply. More precisely, once you have a good knowledge of how to apply date formats using VBA, you can start creating more complex constructions.
To finish this blog post, I introduce one such date formatting macro:
Format Date Using VBA: Add A Carriage Return To Dates
You can add a carriage return in custom date formats. This allows you to display different items of a date in different lines within a single cell.
Let’s see how this looks in practice:
The following screenshot shows an example of a date format with carriage returns. The formatted date is June 20 of 2014, corresponding to the World Cup match between Switzerland and France.
This example works with a date format that only includes month (using the format code mmmm) and year (using the format code yyyy). You can tweak the macro that I introduce below in order to adjust it to your needs and use any other date items or formats.
You can use Visual Basic for Applications for these purposes. The following macro (called “Format_Dates_Carriage_Return”) is the one that I’ve used to achieve the date format shown in the image above.
Some of the elements in this piece of VBA code probably look familiar. The following screenshot shows the elements that I introduce in the previous sections of this Excel tutorial:
There are, however, a few other elements that I don’t introduce in the previous sections of this blog post. These are the following 5:
Element #1: With Statement
You can generally identify a With statement because of its basic syntax. This syntax is roughly as follows:
- Begins with a statement of the form “With object”.
In the case of the Format_Dates_Carriage_Return macro, this opening statement is “With Selection”. As explained above, the Application.Selection property returns the object that is currently selected. When formatting dates using the sample macro above (Format_Dates_Carriage_Return), the selected object is a range of cells.
- Has 1 or more statements in its body.
You can easily identify these 2 statements within the Format_Dates_Carriage_Return macro due to the fact that they’re indented.
- Closes with an End With statement.
The effect of using a With statement is that all of the statements within it refer to the same object or structure. In this case:
- The object to which all of the statements refer to is that returned by the Selection property.
- The statements that refer to the object returned by Selection are:
Statement #1: .NumberFormat = “mmmm” & Chr(10) & “yyyy”.
Statement #2: .RowHeight = .RowHeight * 2.
Statement #3: .WrapText = True.
I explain each of these statements below.
Using the With statement allows you to, among other, simplify the syntax of the macro. I use this statement in other sample macros throughout Power Spreadsheets, including macros that delete blank rows.
Element #2: The Ampersand (&) Operator
The first statement within the With…End With block is:
.NumberFormat = “mmmm” & Chr(10) & “yyyy”
Since, as explained above, this statement works with the object returned by the Application.Selection property, it’s the equivalent of:
Selection.NumberFormat = “mmmm” & Chr(10) & “yyyy”
Most of this statement follows exactly the same structure of (pretty much) all of the other macro examples I include in the previous sections. There are, however, a couple of new elements.
One of those new elements is the ampersand (&) operator. Notice how there are 2 ampersands (&) within this statement:
Within the Visual Basic for Applications environment, the ampersand (&) operator works in a very similar way to how it works in Excel itself.
This means that, within VBA, ampersand (&) is a concatenation operator. In other words, within the Format_Dates_Carriage_Return macro, ampersand (&) concatenates the 3 following expressions:
- Expression #1: “mmmm”.
- Expression #2: Chr(10).
- Expression #3: “yyyy”.
Expression #2 above leads me to the next and last element you need to be aware of in order to understand the first statement within the With…End With block of the sample macro:
Element #3: The Chr Function
The Chr Function returns a string. The string that is returned is determined by the particular character code that you feed as an argument.
In the sample Format_Dates_Carriage_Return macro, the character code is the number 10. This corresponds to a linefeed character. In other words:
“Chr(10)” is what actually adds the carriage return between the date’s month and year.
The second statement within the With…End With block is also new. Let’s take a look at the new element it introduces:
Element #4: Range.RowHeight Property
The Range.RowHeight property allows you to set the height for a row.
In the Format_Dates_Carriage_Return sample macro, this property is used for purposes of doubling the height of the row for which you’re changing the date format. This is done by the statement:
.RowHeight = .RowHeight * 2
The expression to the right side of the equal sign (=) takes the current row height and, using the asterisk (*) operator, multiplies it by 2. The result of applying this property change to the sample chart with the 2014 Brazil World Cup Match Schedule is that a row can now fit the 2 date elements that are separated by the carriage return.
Compare the following 2 screenshots to see the difference this statement makes in the date format. The first image shows what happens when the Format_Dates_Carriage_Return macro is executed without having the statement under analysis. The formatted date, which corresponds to the match between Honduras and Ecuador, is June 20 of 2014.
The image below shows the result of including the Range.RowHeight property for purposes of doubling the row height. The formatted date corresponds to that of the match between Argentina and Iran (June 21 of 2014).
Notice that this format isn’t yet what we want. More precisely, the month and year that correspond to the formatted date are displayed on the same line. Element #5, which I explain below, fixes this.
If the height of the cells whose date format you’re modifying is enough to fit all of the elements/lines, you may not need to include this particular statement in your date-formatting macro. In other cases, you may need to change the factor by which you multiply the current row height. In other words, instead of using the number 2 at the end of the statement (as I do in the sample macro), you may need to use a different number.
The use of the Range.RowHeight property is optional and doesn’t affect the date format of the selected cells. You may choose to omit it from your macros, or work with a different property.
The reason why I use RowHeight in the sample Format_Dates_Carriage_Return is for illustration purposes only. In particular, it ensures that the cell that I format using this macro shows the complete date.
Let’s take a look at the fifth and last of the new elements introduced in the sample Format_Dates_Carriage_Return macro:
Element #5: Range.WrapText Property
The Range.WrapText Property allows you to determine whether Excel wraps the text within the relevant range object. In the sample Format_Dates_Carriage_Return macro, that relevant range object is the range of cells returned by the Application.Selection property.
Within the Format_Dates_Carriage_Return macro, the WrapText property is used for purposes of wrapping the text within its own cell. More precisely, the following statement sets the property to True for all the cells within the range returned by the Selection property:
.WrapText = True
The last image I show when explaining the Range.RowHeight property above displays both the month and the year on the same line. The following image allows you to compare the results obtained when I execute: (i) the macro version that doesn’t include the WrapText property (for the date of the match between Argentina and Iran) and (ii) the macro version that uses the WrapText property (for the match between Germany and Ghana):
Conclusion
This Excel tutorial explains the Range.NumberFormat property in great detail and shows how you can use it for purposes of formatting dates using VBA.
As you’ve probably realized, successfully applying date formats using VBA generally boils down to knowing and understanding the following 2 topics:
- Item #1: The Range.NumberFormat property.
- Item #2: Date format codes.
In addition to reading about these 2 items, you’ve seen 25 different date formatting examples using VBA. Such a long list of examples may seem a little excessive, and there are several similarities between some of the date formats I applied.
However, these 25 examples are evidence of the flexibility you have when formatting dates using VBA. At the same time, they provide a base for you to create your own macros to apply different date formats.
This Excel VBA Date Format Tutorial is accompanied by an Excel workbook containing the data and some versions of the macros I explain above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Books Referenced In This Excel Tutorial
- Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
- Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
- Forum
- VBA Code & Other Help
- Excel Help
- To validate date format in Excel
-
01-29-2008, 11:38 AM
#1
To validate date format in Excel
I am trying to write a validation code to check the date format of cells within three different columns in Excel to ensure that the format matches «dd/mm/yyyy, and if not should give a message. I am new to VBA, and needs help with sample on how to approach it.
Thanks
Lucpian
-
01-29-2008, 11:49 AM
#2
See if this works for you
[vba]
Dim LastRow As Long
Dim cell As Range
Dim col As Range
Dim msg As String
Dim i As LongFor Each col In Range(«A:C»).Columns
LastRow = Cells(Rows.Count, col.Column).End(xlUp).Row
For Each cell In Cells(1, col.Column).Resize(LastRow)If cell.NumberFormat <> «dd/mm/yyy» Then
msg = msg & cell.Address(False, False) & » — » & cell.NumberFormat & vbNewLine
End If
Next cell
Next colMsgBox msg
[/vba]____________________________________________
Nihil simul inventum est et perfectumAbusus non tollit usum
Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I’ve not seen!
James Thurber
-
01-30-2008, 11:46 AM
#3
Originally Posted by xld
See if this works for you
[vba]
Dim LastRow As Long
Dim cell As Range
Dim col As Range
Dim msg As String
Dim i As LongFor Each col In Range(«A:C»).Columns
LastRow = Cells(Rows.Count, col.Column).End(xlUp).Row
For Each cell In Cells(1, col.Column).Resize(LastRow)If cell.NumberFormat <> «dd/mm/yyy» Then
msg = msg & cell.Address(False, False) & » — » & cell.NumberFormat & vbNewLine
End If
Next cell
Next colMsgBox msg
[/vba]
-
01-30-2008, 11:48 AM
#4
Originally Posted by xld
See if this works for you
[vba]
Dim LastRow As Long
Dim cell As Range
Dim col As Range
Dim msg As String
Dim i As LongFor Each col In Range(«A:C»).Columns
LastRow = Cells(Rows.Count, col.Column).End(xlUp).Row
For Each cell In Cells(1, col.Column).Resize(LastRow)If cell.NumberFormat <> «dd/mm/yyy» Then
msg = msg & cell.Address(False, False) & » — » & cell.NumberFormat & vbNewLine
End If
Next cell
Next colMsgBox msg
[/vba]It works when I test one condition, but when I test two formatted conditions it gives an error. Below is the code I wrote with the sample you provided.
Sub ValidationEffDateButton()
Dim strVal As String
Dim rRng As Range
Dim Cols As Integer
‘Dim Rows As Integer
Dim C As Integer
Dim R As Integer
Dim dDate As String
Dim LastRow As Long
Dim cell As Range
Dim col As Range
Dim msg As String
Dim i As Long
‘Set rRng = Range(B).Select
‘Selection.NumberFormat = «dd/mm/yyyy»
For Each col In Range(«B«).ColumnsLastRow = Cells(Rows.Count, col.Column).End(xlUp).Row
For Each cell In Cells(2, col.Column).Resize(LastRow)If ((cell.NumberFormat <> «mm/dd/yy») Or (cell.NumberFormat <> «mm/dd/yyyy»)) Then
‘Sheet1.Cells(«B«).Interior.ColorIndex = 0
‘ MsgBox «Incorrect format»
msg = msg & cell.Address(False, False) & » — » & cell.NumberFormat & vbNewLine
End If
Next cell
Next colMsgBox msg
‘Next
‘If (Len(strVal) <> 13) Then‘ MsgBox «Incorrect value length»
‘Else
‘ MsgBox «Correct value length»‘End If
‘Next
End Sub
Please, what is wrong with this code
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules