2

I have a date column in EXCEL with the date in the format - 1/27/2019. I want to write a script in VBA to extract just the year portion (2019) and put it in another column.

Do I convert the Date into String first? And then split the String using

`Split(date_as_string, "/")

to get the year portion??

How can I convert the Date into String to achieve this? Any other approach to solve this problem is also appreciated.

4 Answers 4

2

If your date column is in true date format then Excel YEAR Function can be used to return value of the year in another column. Date reflected in column in this case is in my system local date format. It may be different in your system but YEAR will work as per your date system.

year_snapshot

EDIT: If you want to go for VBA then example of macro is:

Sub Year_Only()
    Dim yr As String
    yr = Year(Range("A1"))
    Range("B1").Value = yr
End Sub

year_vba

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

Comments

2

Something like

Sub JustYear()
    Dim yr As Long
    yr = Split(Range("A1").Text, "/")(2)
    Range("B1").Value = yr
End Sub

enter image description here

Comments

1

For text representing the year,

range("A1") = format(cdate(date_as_string), "yyyy")

To get a true number representing the year,

range("A1") = val(format(cdate(date_as_string), "yyyy"))

Comments

1

Just use the Year() function:

Option Explicit

Sub test()
    Dim yea As Integer
    Dim r As Range

    Set r = Range("a1")
    yea = year(r.Value)
    Debug.Print yea
End Sub

Comments

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.