Convert string to date for VBA macro

dktechguy112

New Member
Joined
Jul 6, 2012
Messages
1
Hi,

This is my first time posting on the site. I'm new to VBA, and I'm sure this will be easy for you guys.

I am writing a VBA macro that will compare the dates in two columns, and place the difference (numbers of days between them) in a third column. I have a semi working version. This code works fine if the entries are of the type date. The problem is I'm trying to use the code on a workbook that has data in strings.
Many of the strings have a apostrophy in front of them. '02/25/2011
Sometimes the strings are formatted mm/dd/yyyy and sometimes they are formatted m/dd/yyyy

How can I convert these to dates so I can run my macro?
I would prefer to have a solution in VBA. The document I am working with has about 4000 rows.

Code:
Sub CalcDif()
  
  Dim StartDate    As Date
  Dim EndDate      As Date
  
  Dim i As Integer
  For i = 1 To 10
  StartDate = Cells(i, 1).Value
  EndDate = Cells(i, 2).Value
  Cells(i, 3).Value = EndDate - StartDate
  
  If Cells(i, 3).Value < 0 Then
  Cells(i, 3).Value = Cells(i, 3).Value * -1
  End If
  
  Next i
  
End Sub
 

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
try reading the value into a string variable. When you assign the value to a string variable, VBA will strip out the apostrophe.
then convert the string to a date

Dim str1 As String
str1 = Cells(i,1).value
Dim startdate As Date
startdate = CDate(str1)
 
Upvote 0

Forum statistics

Threads
1,214,915
Messages
6,122,214
Members
449,074
Latest member
cancansova

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top