0

I have a macro which pastes dates as text in a column and I have read somewhere, the best solution to convert the text back to dates is to do a search and replace of "/".

If I do this manually in Excel, it works like a breeze. However, when I try to do this with a macro, I do not see the cells being converted to dates.

This is what the macro recorder gave me and what I am trying to use:

Range("t_drill[Date]").Replace What:="/", Replacement:="/", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
4
  • "somewhere" is wrong, your dates may be separated by dots. And this idea builds on a side effect, not very nice. Commented Jun 3, 2019 at 11:51
  • Try to set the Value property of each Cell to CDate() of something. That will cause date formatting. Commented Jun 3, 2019 at 11:53
  • There are no dots, the dates are always separated with "/" and if I manually run search and replace, I can achieve the required result Commented Jun 3, 2019 at 11:55
  • Also, if I manually enter each cell and press "Enter" the text is automatically converted to date. Commented Jun 3, 2019 at 11:58

2 Answers 2

1

Using TextToColumns to convert date:

This is for the date format DMY, if you use a different date format then you will have to make adjustments.

Range("t_drill[Date]").TextToColumns Destination:=Range("t_drill[Date]"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 4), TrailingMinusNumbers:=True

To adjust for different date formats change as required:

MDY :=Array(1, 3)

DMY :=Array(1, 4)

YMD :=Array(1, 5)

MYD :=Array(1, 6)

DYM :=Array(1, 7)

YDM :=Array(1, 8)

Sign up to request clarification or add additional context in comments.

Comments

0

Try setting the Value to the return value of CDate. That changes the formatting of the cell, too.

Dim c As Variant: For Each c In Range("t_drill[Date]").Cells
    c.Value = CDate(c.Value)
Next c

Note: Originally I thought t_drill[Date] is a single cell. I updated my code so that it works for multiple cells.

1 Comment

It is preferred that you add some explanation along with your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.