Date from string vba excel

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

VBA-String-to-Date-1

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.

VBA String to Date Example 1

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.

VBA String to Date Example 1-1

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.

VBA String to Date Example 2

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.

Example 2-1

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.

Example 2-2

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.

Example 3

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.

Example 3-1

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

In this guide, we’re going to show you how to extract date from string in Excel by using formulas and VBA.

Download Macro-Free Workbook

Download Workbook

Note that, there isn’t a single formula or approach that can handle all scenarios. Extracting dates from strings that is not following a specific pattern is one of the few things Excel cannot handle. You almost need an AI to be able to encapsulate every possible scenario. The good thing is that we are going to offer you multiple ways to parse the date.

Data

We have generated strings that included dates using slash (/) as day-month-year separator and using US-type (month/day/year) dates. Thus, if your date format is different, you may see errors (empty cells because of IFERROR functions) after opening our file. Update the dates according to your localization settings. Also, do not forget to update the slash characters if your data includes dates with other separators like dot (.) or hyphen (-).

Formula for extracting date from string

The logic behind the formulas we will introduce is to locate the pattern that resembles a date. Once the potential date value’s location is found, we can parse it easily.

The tricky part is to select a correct pattern which is suitable with your raw data. A date can be in many forms:

  • 01/07/2022
  • 1/7/2022
  • 1/7/22
  • 1/12/2022
  • 12/1/2022
  • 12/1
  • 12/2022

If your raw data contains more than one or two patterns the formula solution may not work unless you do not want to create extremely long formulas.

In our sample formula, we used «01/07/2022» format. Thus, we assume the date values in the data to follow the rules below:

  • US Date format
  • Month and day are two digits
  • Year uses four digits
  • Each unit is separated by slash «/»
  • A date contains 10 characters including delimiters

Based on these assumptions, we can use «/??/» keyword with the SEARCH function to locate the date. The SEARCH function can use the wildcards to locate a pattern instead of an exact string. Because a question mark (?) represents a single character, «/??/» refers 2 characters between slashes just like the day part of a date.

The SEARCH function returns the position number where the keyword starts if there is a matching string.

Change the pattern keyword based on your data. For example, «.??.» or ??-????

Subtract the position by 2 to find where the date starts.

Once the date is located, you can use the MID function to parse it. The MID function needs the position of the string you want to parse and its length. Because we assume the date format is «mm/dd/yyyy», the length will be 10.

=MID(<data>,SEARCH(«/??/»,<data>,1)-2,<date length>)

Although, the formula looks like its working, it will return any characters matching the pattern i.e. letters.

This is where the DATEVALUE function comes handy. The function can convert text-based date/time values into actual dates. The function returns #VALUE! error if the supplied text is not a valid date. You can use the DATEVALUE function to verify dates. The IFERROR function can wrap the formula to cover scenarios without date.

=IFERROR(DATEVALUE(MID(<data>,SEARCH(«/??/»,<data>,1)-2,<date length>)),»»)

Although this formula is suitable for our example, it’s obvious that it will fail for others. A few examples:

  • A single-digit month date without a space in front: cells C6, C9
  • A text containing similar string before the actual date: cell C8
  • Single-digit month and days: cells between C19 and C25
  • Double-digit years: cells between C26 and C32

How to extract date from string in Excel w Formula

Using VBA for extracting date from string

An alternative to the Excel formulas is to create your own function by using VBA. The VBA-based functions, also known as user defined functions (UDF), can be used as regular formulas once they are written and saved properly.

VBA has two dedicated methods which give a particular advantage for extracting a date from a string.

  1. The Split method can separate words or strings separated by spaces.
  2. The DateValue method can validate dates better than its formula counterpart.

Obviously, this method is not foolproof neither. The date values should be separated from other text by a space character. On the other hand, you are not limited with a certain pattern. Thus, number of digits in units are not significant.

You can copy and paste the following code into a module and start using it right away. Just do not forget to save your Excel file as an Excel Macro-Enabled Workbook (XLSM) rather than a regular workbook.

Function ExtractDate(str As String)
    
    On Error GoTo errHandler
    Dim i As Integer, dt As Date, arr() As String, temp As String
    
    dt = 0
    arr = Split(str)
    
    For i = LBound(arr) To UBound(arr)
        temp = arr(i)
        If IsDate(temp) And Len(temp) > 5 Then
            dt = DateValue(temp)
            Exit For
        End If
    Next i

cont:
    ExtractDate = dt
    Exit Function
    
errHandler:
    dt = 0
    Resume cont
End Function

How to extract date from string in Excel w VBA

Once you paste the code, use it in your worksheet by giving a reference to the data cell.

=IF(ExtractDate(<data>)=0,»»,ExtractDate(<data>))

The equals to zero (0) condition is to avoid zero (0) values. Otherwise, the function will return zero (0) when it cannot find a valid date.

How to extract date from string in Excel w UDF

As you can see either approach is far from perfection. However, you have more than one option to extract date from string.

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.

VBA Date MsgBox Number

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

VBA Date MsgBox Date

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!

VBA_Date MsgBox DateString

If we were to omit the year entirely, Excel assumes the current year.

VBA Date MsgBox DateString NoYear

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Содержание

  1. DateValue function
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. VBA String to Date
  8. Excel VBA String to Date
  9. How to Convert String Values to Date?
  10. Example #1
  11. Example #2
  12. Example #3
  13. Things to Remember
  14. Recommended Articles
  15. excel vba string to date
  16. 4 Answers 4

DateValue function

Returns a Variant (Date).

Syntax

DateValue(date)

The required date argument is normally a string expression representing a date from January 1, 100, through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date format that you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.

If the year part of date is omitted, DateValue uses the current year from your computer’s system date.

If the date argument includes time information, DateValue doesn’t return it. However, if date includes invalid time information (such as «89:98»), an error occurs.

For date, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. If the supplied date is Hijri, the argument date is a String representing a date from 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999).

Example

This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant or Date variable, for example, MyDate = #2/12/69#.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA String to Date

Excel VBA String to Date

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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA String to Date (wallstreetmojo.com)

How to Convert String Values to Date?

Example #1

Code:

The above code defines the variable “k” as the “String” data type. We have assigned this variable the value of “10-21.”

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 VBA CDATE VBA The 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:

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:

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:

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:

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 excel Date Format In Excel The 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:

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 stringVBA 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: –

Источник

excel vba string to date

Windows 10 Pro, Regional Settings to UK English. In Excel VBA I have a string «02/05/2017 16:30» That, in the UK, means «02 May 2017 16:30»

But VBA turns this to US format somehow and in the cell puts «05/02/2017 16:30»

The VBA code is like this

I can use CDate to get around this but CDate but that requires extra code to determine which cells are dates and which aren’t, whereas the implicit conversion works for all types.

4 Answers 4

Use a Date variable instead, and always provide your date in MDY in VBA.

AFAIK in VBA you must always work the ‘American way’, with dates MDY. It does NOT follow regional settings. Which is good, because that enables running the same code on heterogeneous environments.

This is some workaround in the VBA code:

It takes the date as a string and it splits it by / . Then it takes the year, the month and the day and it builds a new date with the help of DateSerial() . DateSerial MSDN.

In cases like this, make sure that you are passing the correct date to excel and there you may change the format through something as easy as this:

To make sure, that you are passing the correct date, simply try Month(YourDate) over the date or Day(YourDate) .

I rather use the built-in VBA functions DateSerial(year, month, day) and TimeSerial(hour, min, sec).

You can then set the number formatting on the Excel cell to your liking.

I assume this is faster because there is not need to translate any string beforehand. More importantly for me as a programmer, the parameters are explicit. I don’t have to worry about different regional setting.

Источник

VBA convert string to date in Excel, we use VBA CDate data type conversion function. In the following article let us see an example and also the step by step instructions to run vba code in the visual basic editor(VBE) window. You can find link at the end of the session to know more about CDate VBA function.

Example macro code to convert string to date

Let us see the example VBA macro procedure code to convert string to date. Declared two variables. The first one is sInput to assign input string type value and the second one is iResult. In the below example we have used CDate function. Ensure to enter specified input in string format.

'VBA Convert String type to Date type value
Sub VBAF1_Convert_String_To_Date()

    'Variable Declaration
    Dim sInput As String, iResult As Date
       
    'Specify Input of type string
    sInput = "01/01/2019"
    
    'Convert String to Date
    sResult = CDate(sInput)
        
    MsgBox "Successfully string has converted to date.", vbInformation, "VBAF1"
 
End Sub

Output: Here is the output screenshot message of above example macro code for your reference.
VBA Convert String to Date

Multiple Example Macro Codes for String to Date Conversion

Here are the different example macro codes for string to date conversion. When we writing programming, we write code based on requirement. Date has different formats. Depending on the scenario we use required format. Let us see some examples here for your reference.

Note: Specified input (Sample Input Date) should be in string format.

Example 1: String To Date format dd-mmm-yyyy conversion in VBA

Format(CDate(Sample Input Date), "dd-mmm-yyyy")

Example 2: VBA String To Date format dd/mm/yyyy conversion

Format(CDate(Sample Input Date), "dd/mm/yyyy")

Example 3: String To Date format yyyymmdd conversion in VBA

Format(CDate(Sample Input Date), "yyyymmdd")

Example 4: VBA String To Date Time conversion

Format(CDate(Sample Input Date), "dd-mmm-yyyy hh:mm:ss")

Example 5: String To Date number format conversion in VBA

 CDbl(CDate(sInput))
 'or
 CLng(CDate(sInput))

Instructions to Run VBA Macro Code or Procedure:

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

Instructions to run VBA Macro Code

Other Useful Resources:

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

VBA Tutorial VBA Functions List VBA Arrays in Excel VBA Tables and ListObjects

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

vba cdateVisual 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!

Like this post? Please share to your friends:
  • Date formatting in vba excel
  • Date formatting excel formula
  • Date format in excel will not change
  • Date format in excel cells
  • Date format excel problem