Каждая функция привнося выражение к определенному тип данных.
Синтаксис
CBool(
выражение
)
CByte(
выражение
)
CCur(
выражение
)
CDate(
выражение
)
CDbl(
выражение
)
CDec(
выражение
)
CInt(
выражение
)
CLng(
выражение
)
CSng(
выражение
)
CStr(
выражение
)
CVar(
выражение
)
Обязательный аргумент выражениеаргумент — это любое строковое выражение или числовое выражение.
Возвращаемые типы
Тип возвращаемого значения определяется по имени функции в соответствии со следующей таблицей:
Функция |
Тип возвращаемого значения |
Диапазон аргумента |
CBool |
Boolean |
Любое допустимое строковое или числовое выражение. |
CByte |
Byte |
От 0 до 255. |
CCur |
Currency |
От -922 337 203 685 477,5808 до 922 337 203 685 477,5807. |
CDate |
Date |
Любое допустимое выражение даты. |
CDbl |
Double |
От -1,79769313486231E308 до |
CDec |
Decimal |
+/-79 228 162 514 264 337 593 543 950 335 для чисел без дробной части. Для чисел с 28 десятичными знаками допустимый диапазон составляет |
CInt |
Integer |
От -32 768 до 32 767, дробная часть округляется. |
CLng |
Long |
От -2 147 483 648 до 2 147 483 647, дробная часть округляется. |
CSng |
Single |
От -3,402823E38 до -1,401298E-45 для отрицательных значений и от 1,401298E-45 до 3,402823E38 для положительных. |
CStr |
String |
Результат, возвращаемый функцией CStr, зависит от аргумента выражение. |
CVar |
Variant |
Тот же диапазон, что и для числов Double. Такой же диапазон, как и для строк для не числов. |
Замечания
Если передаваемое функции выражение находится за пределами диапазона типа данных, в который оно преобразуется, возникает ошибка.
Как правило, функции преобразования типов используются в тексте программ для того, чтобы указать, что результатом той или иной операции должны стать данные определенного типа, а не типа, заданного по умолчанию. Например, с помощью функции CCur можно принудительно перейти к вычислениям в денежном формате в тех случаях, в которых обычно используются действия с числами с обычной точностью, двойной точностью или с целыми числами.
Функции преобразования типа данных следует использовать вместо функции Val для преобразования типов данных в приложениях, поддерживающих различные региональные стандарты. Например, при использовании функции CCur десятичные разделители, разделители групп разрядов и параметры денежных единиц распознаются в соответствии с языковыми и региональными параметрами компьютера.
Если дробная часть целого числа строго равна 0,5, функции CInt и CLng всегда округляют результат до ближайшего четного числа. Например, 0,5 округляется до 0, а 1,5 — до 2. В отличие от функций CInt и CLng, в функциях Fix и Int дробная часть не округляется, а отбрасывается. Кроме того, функции Fix и Int всегда возвращают значение того же типа, что и переданное им выражение.
Для определения возможности преобразования даты в дату или время используется функция IsDate. Функция CDate распознает литералы даты и времени, а также некоторые числа, которые находятся в диапазоне допустимых дат. При преобразовании числа в дату преобразуется целая часть числа. Дробная часть преобразуется во время суток, начиная с полуночи.
CDate распознает форматы даты в соответствии с языковые стандарты системным параметром. Правильный порядок дат, месяца и года может быть определен не в том формате, который не является распознаемой датой. Кроме того, длинный формат даты не распознается, если он также содержит строку дней недели.
Функция CVDate предназначена для обеспечения совместимости с предыдущими версиями Visual Basic. Синтаксис функции CVDate идентичен синтаксису функции CDate, однако функция CVDate возвращает не результат типа Date, а результат типа Variant с подтипом Date. Поскольку теперь реализован встроенный тип Date, необходимость в функции CVDate отпадает. Того же результата можно добиться, преобразовав выражение в тип Date и присвоив это значение переменной типа Variant. Этот способ позволяет преобразовать все прочие встроенные типы в эквивалентные им подтипы Variant.
Примечание: Функция CDec не возвращает отдельный тип данных. Вместо этого она всегда возвращает результат типа Variant, значение которого преобразовано в подтип Decimal.
Примеры запросов
|
|
SELECT SalePrice,FinalPrice,CBool(SalePrice>FinalPrice) AS Expr1 FROM productSales; |
Возвращает значения «ЦенаПродажи», «ПоследняяЦена» и оценивает, превышает ли Цена конечная цена. Возвращает «-1», если истина, и «0», если ложь. |
SELECT ProductID, CByte(Quantity) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле «Количество» в формат «Количество» и отображает в столбце Expr1 значение «ProductID», преобразует значения в поле «Количество» в формат «Валюта» и отображает в столбце Expr1. |
SELECT ProductID, CDate(DateofSale) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения поля DateofSale в формат Date и отображает значения в столбце Expr1. |
SELECT ProductID, CDbl(Discount) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле Discount в формат Double и отображает значения в столбце Expr1. |
SELECT ProductID, CInt(Discount) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле Discount в формат Integer и отображает значения в столбце Expr1. |
SELECT ProductID, CLng(Discount) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле Discount в формат Long и отображает в столбце Expr1. |
SELECT ProductID, CSng(Discount) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле «Скидка» в single format и отображает в столбце «Expr1». |
SELECT ProductID, CStr(Discount) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле Discount в строковом формате и отображает значения в столбце Expr1. |
SELECT ProductID, CVar(Discount) AS Expr1 FROM productSales; |
Возвращает значение «ProductID», преобразует значения в поле «Скидка» в значение Double для числных значений и String для не числных значений. |
Примеры VBA
Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.
Функция CBool
Совет: В Access 2010 и более поздних версиях есть построитель выражений с поддержкой IntelliSense, который помогает создавать выражения.
В этом примере функция CBool используется для преобразования выражения в тип Boolean. Если выражение разрешается в ненулевое значение, функция CBool возвращает значение True; в противном случае она возвращает значение False.
Dim A, B, Check
A = 5: B = 5 ' Initialize variables.
Check = CBool(A = B) ' Check contains True.
A = 0 ' Define variable.
Check = CBool(A) ' Check contains False.
Функция CByte
В этом примере функция CByte используется для преобразования выражения в тип Byte.
Dim MyDouble, MyByte
MyDouble = 125.5678 ' MyDouble is a Double.
MyByte = CByte(MyDouble) ' MyByte contains 126.
Функция CCur
В этом примере функция CCur используется для преобразования выражения в тип Currency.
Dim MyDouble, MyCurr
MyDouble = 543.214588 ' MyDouble is a Double.
MyCurr = CCur(MyDouble * 2)
' Convert result of MyDouble * 2 (1086.429176) to a
' Currency (1086.4292).
Функция CDate
В этом примере функция CDate используется для преобразования выражения в тип Date. Как правило, не рекомендуется определять дату и время в виде строк (как показано в этом примере). Вместо этого пользуйтесь литералами даты и времени, например #2/12/1969# и #4:45:23 PM#.
Dim MyDate, MyShortDate, MyTime, MyShortTime
MyDate = "February 12, 1969"
' Convert to Date data type.
MyShortDate = CDate(MyDate)
MyTime = "4:35:47 PM"
' Convert to Date data type.
MyShortTime = CDate(MyTime)
Функция CDbl
В этом примере функция CDbl используется для преобразования выражения в тип Double.
Dim MyCurr, MyDouble
MyCurr = CCur(234.456784)
' Convert result to a Double.
MyDouble = CDbl(MyCurr * 8.2 * 0.01)
Функция CDec
В этом примере функция CDec используется для преобразования выражения в тип Decimal.
Dim MyDecimal, MyCurr
MyCurr = 10000000.0587 ' MyCurr is a Currency.
MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal.
Функция CInt
В этом примере функция CInt используется для преобразования выражения в тип Integer.
Dim MyDouble, MyInt
MyDouble = 2345.5678 ' MyDouble is a Double.
MyInt = CInt(MyDouble) ' MyInt contains 2346.
Функция CLng
В этом примере функция CLng используется для преобразования выражения в тип Long.
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45
MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)
' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)
' MyLong2 contains 25428.
Функция CSng
В этом примере функция CSng используется для преобразования выражения в тип Single.
Dim MyDouble1, MyDouble2, MySingle1, MySingle2
' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)
' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)
' MySingle2 contains 75.34216.
Функция CStr
В этом примере функция CStr используется для преобразования выражения в тип String.
Dim MyDouble, MyString
MyDouble = 437.324 ' MyDouble is a Double.
MyString = CStr(MyDouble)
' MyString contains "437.324".
Функция CVar
В этом примере функция CVar используется для преобразования выражения в тип Variant.
Dim MyInt, MyVar
MyInt = 4534 ' MyInt is an Integer.
MyVar = CVar(MyInt & "000")
' MyVar contains the string 4534000.
I have a column of dates (column A) stored as text in the format yyyy-mm-dd
which I’m trying to convert to dates, ultimately so that I can do look ups against them.
I’ve read a few topics on here and tried some of the suggestions, but I can’t get anything to work. One was using:
Columns("A").Select
Selection.NumberFormat = "date"
This changed the format of the cells to date but didn’t actually change the format of the value which was still stored as text.
My understanding is that I need to use CDate() to change the format of the value from text to date. I’ve tried something like this:
Dim c As Range
For Each c In ActiveSheet.UsedRange.columns("A").Cells
c.Value = CDate(c.Value)
Next c
Which gives me a type mismatch error. I wondered if this was because I was trying to save date values back into a non-date formatted cell so I tried combining it with the .NumberFormat = «date» above, which didn’t work either.
Any suggestions would be appreciated.
Teamothy
1,9903 gold badges15 silver badges24 bronze badges
asked Dec 4, 2013 at 12:20
2
You can use DateValue
to convert your string to a date in this instance
Dim c As Range
For Each c In ActiveSheet.UsedRange.columns("A").Cells
c.Value = DateValue(c.Value)
Next c
It can convert yyyy-mm-dd
format string directly into a native Excel date value.
answered Dec 4, 2013 at 12:48
SamSam
7,2053 gold badges25 silver badges37 bronze badges
2
You can quickly convert a column of text that resembles dates into actual dates with the VBA equivalent of the worksheet’s Data ► Text-to-Columns command.
With ActiveSheet.UsedRange.Columns("A").Cells
.TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, FieldInfo:=Array(0, xlYMDFormat)
.NumberFormat = "yyyy-mm-dd" 'change to any date-based number format you prefer the cells to display
End With
Bulk operations are generally much quicker than looping through cells and the VBA’s Range.TextToColumns method is very quick. It also allows you the freedom to set a MDY vs. DMY or YMD conversion mask that plagues many text imports where the date format does not match the system’s regional settings. See TextFileColumnDataTypes property for a complete list of the available date formats available.
Caveat: Be careful when importing text that some of the dates have not already been converted. A text-based date with ambiguous month and day integers may already been converted wrongly; e.g. 07/11/2015 may have been interpreted as 07-Nov-2015 or 11-Jul-2015 depending upon system regional settings. In cases like this, abandon the import and bring the text back in with Data ► Get External Data ► From Text and specify the correct date conversion mask in the Text Import wizard. In VBA, use the Workbooks.OpenText method and specify the xlColumnDataType.
answered Jun 3, 2015 at 2:11
1
Besides other options, I confirm that using
c.Value = CDate(c.Value)
works (just tested with the description of your case, with Excel 2010). As for the reasons for you getting a type mismatch error, you may check (e.g.) this.
It might be a locale issue.
answered Dec 4, 2013 at 14:05
0
Perhaps:
Sub dateCNV()
Dim N As Long, r As Range, s As String
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
Set r = Cells(i, "A")
s = r.Text
r.Clear
r.Value = DateSerial(Left(s, 4), Mid(s, 6, 2), Right(s, 2))
Next i
End Sub
This assumes that column A contains text values like 2013-12-25 with no header cell.
answered Dec 4, 2013 at 12:31
Gary’s StudentGary’s Student
95.3k9 gold badges58 silver badges98 bronze badges
I had a very similar issue earlier. Unfortunately I looked at this thread and didn’t find an answer which I was happy with. Hopefully this will help others.
Using VBA.DateSerial(year,month,day)
you can overcome Excel’s intrinsic bias to US date format. It also means you have full control over the data, which is something I personally prefer:
function convDate(str as string) as Date
Dim day as integer, month as integer, year as integer
year = int(mid(str,1,4))
month = int(mid(str,6,2))
day = int(mid(str,9,2))
convDate = VBA.DateSerial(year,month,day)
end function
answered Jan 3, 2019 at 17:16
SancarnSancarn
2,54318 silver badges43 bronze badges
This code is working for me
Dim N As Long, r As Range
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To N
Set r = Cells(i, "B")
r.Value = CDate(r.Value)
Next i
Try it changing the columns to suit your sheet
answered Oct 28, 2015 at 15:47
2
To the OP…
I also got a type mismatch error the first time I tried running your subroutine. In my case it was cause by non-date-like data in the first cell (i.e. a header).
When I changed the contents of the header cell to date-style txt for testing, it ran just fine…
Hope this helps as well.
answered Feb 20, 2015 at 18:10
Blast from the past but I think I found an easy answer to this. The following worked for me. I think it’s the equivalent of selecting the cell hitting F2 and then hitting enter, which makes Excel recognize the text as a date.
Columns("A").Select
Selection.Value = Selection.Value
answered Aug 16, 2018 at 13:02
1
I’ve got rid of type mismatch by following code:
Sub ConvertToDate()
Dim r As Range
Dim setdate As Range
'in my case I have a header and no blank cells in used range,
'starting from 2nd row, 1st column
Set setdate = Range(Cells(2, 1), Cells(2, 1).End(xlDown))
With setdate
.NumberFormat = "dd.mm.yyyy" 'I have the data in format "dd.mm.yy"
.Value = .Value
End With
For Each r In setdate
r.Value = CDate(r.Value)
Next r
End Sub
But in my particular case, I have the data in format «dd.mm.yy»
answered Jun 1, 2017 at 8:36
For DD-MM-YYYY here is a simple workaround to manage string and dates:
insert the date into the string via DD-MMM-YYYY
for example 01-11-2017 -> 01-Nov-2017
U can use the FORMAT(date, «dd-mmm-yyyy») to input dates into a string from the spread sheet.
Later, when you output it from a string, it will not confuse the days and months.
answered Sep 5, 2017 at 0:37
GilcoGilco
1,31612 silver badges13 bronze badges
2
Solved the issue for me :
Range(Cells(1, 1), Cells(100, 1)).Select
For Each xCell In Selection
xCell.Value = CDate(xCell.Value)
Next xCell
answered Jul 4, 2019 at 13:24
Visual Basic for Applications or VBA is a scripting language that enables automation of tasks in the Microsoft Office suite of products. It’s also an event driven programming language which contains a lot of useful functions. It is leveraged by programmers to create effective and efficient macros. Read more about what VBA can help you do, in this tutorial. Today, we are going to take it a step ahead in this intermediate tutorial and take a look at a vital date function namely CDate(). This function is used to convert the strings or numbers into date format.
We assume that you have working knowledge of MS Excel and VBA. If you are new to this concept, we suggest you to go through our introductory course to Excel VBA.
Date Systems in Microsoft Excel
Date and time functions are frequently used in MS Excel and VBA. Therefore, it’s important that you know the basic concepts of date and time functions if you want to manipulate and use them in your programs. Please note that MS Excel stores date as sequential numbers known as serial values. MS Excel considers time to be a part of a day and it is stored as decimal fractions. Dates and times can be added and subtracted. Therefore they can be included in many calculations and VBA programs. That is you can compare two dates or subtract one date from another. You can learn more about this in our Excel course.
There are two date systems in MS Excel- the 1900 and 1904. By default Microsoft Excel for Windows is 1900 and for Macintosh is 1904. You can change the date system if you want by clicking on Tools menu. Then click “Options” and choose “Calculation tab.” In Calculation tab, select or clear the 1904 date system checkbox.
You should also be aware that, the date system will be changed automatically when you open an Excel worksheet from another platform. That is when you open a worksheet created in Excel for Macintosh, while working in Excel for Windows, the system will automatically select the 1904 date system.
The following table shows the first and last date for each date system.
Date system |
First date |
Last date |
1900 | January 1, 1900
(serial value 1) |
December 31, 9999
(serial value 2958465) |
1904 | January 2, 1904
(serial value 1) |
December 31, 9999
(serial value 2957003) |
How Microsoft Excel Interprets Two-Digit Years
If you are using Microsoft Windows 2000 or later versions, the regional options in Control Panel controls how Excel interprets two-digit years. If you want MS Excel to assume the year values as you intended it to be, enter the year as a four digit value. The reason is, Excel will not interpret century.
For example instead of entering “00” for the year 2000, you should enter the all the four digits “2000”.
How MS Excel Interprets Year Portion of the Date Entered as a String or Text
- 00 through 29– When you enter the date as 3/24/14, Excel assumes the date is March 24, 2014.
- 30 through 99– Here MS Excel interpret the two-digit year values 30 through 99 as the years 1930 through 1999. That is if you enter the date in the cell as 3/24/94, Excel will interpret the date as March 24, 1994.
Microsoft Excel VBA has many date and time functions.A few of the important ones being Date(), Day(), Now(), DateAdd(), TimeSerial() and DateSerial(). It also has equal number of data type conversion functions. An important data type conversion function that is frequently used in VBA programming is CDate(). To learn more about Excel VBA, you can check out this course.
What is CDate() Function
CDate identifies date and time literals (along with some numbers that fall inside the range of acceptable dates) and converts them to the date date type. If there a fractional part of the number it is converted to a time of day starting from midnight.
The CDate() function identifies date formats depending on the locale setting of your system. The correct order of day, month and year will not be realized by this function if it is entered in a format other than one of the recognized date settings. If the year is not specified in the date, then the current year is used. Also note that a long date format is not recognized if it also contains the day-of-the-week string.
VBA CDate()converts a value of any data type, string or integer, into a date type. The syntax of this date function looks like this
CDate(expression)
Here the argument expression is mandatory. When you enter a valid date and time expression this function converts it into type Date. Let’s make this concept clear using a simple example.
Example 1:
Function FnCDate () Dim strDate_1 Dim intDate_1 Dim strTime_1 strDate_1 = "January 24, 2014" intDate_1 = #12/03/2014# strTime_1 = "15:30:15 PM" MsgBoxCDate(strDate_1) MsgBoxCDate(intDate_1) MsgBoxCDate(strTime_1) End Function
In the program, three variables strDate_1, IntDate_1 and strTime_1 are declared. These variables are assigned values “January 24, 2014”, #12/03/2014# and “15:30:15 PM” respectively. The variables are passed through the CDate() function. The output is as follows.
For the MsgBoxCDate(strDate_1) the output displayed is “24-01-2014.”
For the MsgBoxCDate(intDate_1) the output displayed is “03-12-2014.”
For the MsgBoxCDate(strTime_1) the output displayed is “15:30:15.”
How to Convert Text String to Date in MS Excel VBA Using CDate() Function
When you are working with data that contains dates, you need to have a clear idea about how to use the date data type. From MS Excel versions 2000 onwards, you have VBA to automate tasks that you would otherwise perform manually. This is normally done with the help of macros (you can learn more about VBA macros in this course). VBA CDate()function is one of the most commonly used date functions to convert a date stored in a “String” variable into a date data type. The example given below will help make the concept clear.
Open your MS Excel and enter the date in cell A1 in the following format:
March 24, 2014
To open the “Visual Basic Editor”, click the “Developer” tab and then “Visual Basic”. In the editor click “Insert” menu and click “Module.” This will insert a new code module. Here is where you write the code.
Example 2:
Sub converTextToDate() Dim Current_DateAs Date Dim Date_StringAs String Range("A1").Select Date_String = Range("A1").Value Current_Date = CDate(date_String) Range("C1").Select Range("C1").Value = Current_Date End Sub
Let’s take a closer look at the program.
In this program, two variables, “Current_Date” and “Date_String” have been declared as type Date and String respectively. Range(“A1”).Select will get the date entered in the cell A1.Date_String = Range(“A1”).Valuestores in the “string” variable Date_String.Current_Date=CDate(date_string) converts the string into Date data type and stores it in the variable “Current_Date”.The last two steps will move the cursor to cell C1 and display the date in column C1 when the procedure is executed.
In the next program, we take a look at how to compare two dates in VBA using CDate() function.
Note that to compare dates in VBA, you need to have dates stored in variables of type “Date”. However, if the dates that you are comparing are entered as numbers or string, you need to convert them using CDate() function. “If statement” is used to compare the dates. The following example helps make the concept clear.
Example 3:
Public Sub CompareDates() Dim d1, d2 As Date d1 = CDate("24/1/2013") d2 = CDate("24/1/2014") If (d1 < d2) Then Debug.Print "Date 1 occurs earlier than date 2." If (d1 > d2) Then Debug.Print "Date 1 occurs later than date 2." If (d1 = d2) Then Debug.Print "Date 1 is the same as date 2." End Sub
If you happen to work regularly on data which contains date columns, it is always wise to create a macro. Call that Macro whenever you want to delete rows in your table. Here is an example which deletes the dates prior to “12/30/2011.”
Example 4:
Sub DeleteRowbyDate() Dim x As Long For x = 1 To Cells.SpecialCells(xlCellTypeLastCell).Row Debug.Print Cells(x, "B").Value If CDate(Cells(x, "B")) <CDate("12/29/2011") Then Cells(i, "B").EntireRow.delete End If Next i End Sub
In this example all rows with dates less than “12/29/2011” will be deleted.For example, If you want to delete all the rows prior to December 29 2012 from your table, then you will have to change the line to:
If CDate(Cells(x, "B")) <CDate("12/29/12")
We hope this gives you a good understanding of the wide range of options available to you while working with dates in Excel and with VBA. As usual, the best way to get familiar with these formula, is to try them out for yourself. If you’d like, Mr Excel has a good course with plenty of examples to help you on your way!
Return to VBA Code Examples
This short tutorial will demonstrate how to convert a String to a Date in VBA.
Dates in Excel are stored as numbers, and then formatted to show as a date. Day 1 in the world of Excel was the 1st January 1900 (Windows default) or 1st January 1904 (Macintosh default) – which means that the 5th August 2021 is day 44413 since the 1st January 1900. To convert a string to a date in Excel, we first need to convert the string to a number, and then convert that number to the date.
CDate Function
We can use a function called CDate in VBA to convert a string to a date.
Sub ConvertDate()
Dim dte As Single
Dim strD As String
strD = "05/10/2020"
dte = CDate(strD)
MsgBox dte
End Sub
As we have declared a numeric variable (dte as Single), the msgbox will return the number that refers to the date entered.
It is important that we enter the year using all 4 of the year digits (ie 2020 and not just 20), otherwise the number returned might not be as expected. Excel does not interpret the year part of the date – this is controlled by the Control Panel of our PC.
However, if we declare the variables as a date variable, the message box will return the number converted to a date.
Sub ConvertDate()
Dim dte As Date
Dim strD As String
strD = "05/10/2020"
dte = CDate(strD)
MsgBox dte
End Sub
We can take this one step further and format the date to the type of date format that we would like to see.
Sub ConvertDate()
Dim dte As String
Dim strD As String
strD = "05/10/2020"
dte = Format(CDate(strD), "dd mmmm yyyy")
MsgBox dte
End Sub
In this example, we are converting the string to a date, and then back to a string again!
If we were to omit the year entirely, Excel assumes the current year.
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!
Learn More!
In VBA, there is a method through which we can convert a given string to a date. The method is known as the CDATE function in VBA. It is an inbuilt function in VBA, and the parts required for this function are first to convert the string to a number, then convert the given number to date. The result format depends on the system date format only.
One of the common problems we all face with Excel is “Date & Time,” which are often stored as text values and go unnoticed initially. But, when they require the use of that time, we know that those values are stored as text and don’t know how to deal with them. That is because “Date & Time” are two combined things in one element. But, once those values as text values are stored, it is a pain to work with.
Table of contents
- Excel VBA String to Date
- How to Convert String Values to Date?
- Example #1
- Example #2
- Example #3
- Things to Remember
- Recommended Articles
- How to Convert String Values to Date?
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA String to Date (wallstreetmojo.com)
How to Convert String Values to Date?
You can download this VBA String to Date Excel Template here – VBA String to Date Excel Template
Example #1
Once the VBA variable is declaredVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more and assigned as String, anything assigned to that variable will be treated as a string only. For example, look at the below code.
Code:
Sub String_To_Date() Dim k As String k = "10-21" MsgBox k End Sub
The above code defines the variable “k” as the “String” data type. We have assigned this variable the value of “10-21.”
Run the code and see what we get in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
We only got the value as 10-21. But usually, these values are dates, not string values. So, even though the data type assigned is “String,” we can still convert to date using the data type conversion function CDATE VBAThe VBA CDATE Function converts a variable (text or string) to the date data type. VBA displays the run-time 13 error if it is unable to convert a value to Date & Time.read more.
Code:
Sub String_To_Date() Dim k As String k = "10-21" MsgBox CDate(k) End Sub
In the above, before we show the variable “k” result in the message box. Then, we assigned the CDATE function. Then, we made a small adjustment. Finally, let us see how big an impact it makes.
Now, we would see the result as “Date” no longer as a “String” value.
Example #2
Look at the below code.
Code:
Sub String_To_Date() Dim k As String k = 43599 MsgBox k End Sub
The above code would show the result as “43599,” as we assigned above.
But once we use the CDATE function, it will convert to the date value.
Code:
Sub String_To_Date() Dim k As String k = 43599 MsgBox CDate(k) End Sub
The result after applying the CDATE function is as follows.
Since Excel stored the date as serial numbers, our assigned serial number 43599 equals the date 05/14/2019 when the date format is applied.
To read the date accurately, we can apply the format to the date as “DD-MMM-YYYY.”
Code:
Sub String_To_Date1() Dim k As String Dim DateValue As Date k = 43599 DateValue = CDate(k) MsgBox Format(DateValue, "DD-MMM-YYYY") End Sub
We have declared one extra variable to store the result in the above. For this variable, we have applied the CDATE conversion function.
Next, we used the FORMAT function to apply the “DD-MMM-YYYY” format. The result will be as shown below.
With this, we can read the daypart and month part. Of course, it also depends on your system date format in excelThe date format in Excel can be changed either from the “number format” of the Home tab or the “format cells” option of the context menu.read more. Since my system date format was “MM-DD-YYYY,” it was showing like that, but that should not hinder the format.
Example #3
Now, we will see how dates format as text values in worksheet cells. Below is the image of the dates stored as text in a worksheet.
In column A from A2 to A12, we have date-looking values, but when we look at the format tab, it shows “Text” format. So, now we need to convert these values from text to date.
Below is the code we have written to convert the text-formatted date values to actual dates.
Code:
Sub String_To_Date2() Dim k As Long 'Data is in more than one cell, so need to loop through each cell 'Open For Loop For k = 2 To 12 'Data starts from 2nd row and ends at 12th row, so 2 to 12 Cells(k, 2).Value = CDate(Cells(k, 1).Value) Next k End Sub
If you run the code, it will give us the below result.
Things to Remember
- The CDATE is a data type conversion function that can convert VBA stringString functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions.read more stored date to actual date values.
- The result of the CDATE function format depends on the system date format only.
- Dates are stored as serial numbers in Excel, so formatting is required to show them as dates.
Recommended Articles
This article has been a guide to VBA String to Date. Here, we discuss converting date stores in string values to date format in Excel VBA using the CDATE function and examples. You can learn more about VBA functions from the following articles: –
- VBA Format Date
- Split String into Array in VBA
- Set Range in VBA
- Get Value from Cell in VBA