I have an excel workbook with several sheets. What I need to do is transfer the year from a column in one sheet to another sheet. I can get the column to transfer over fine, but I can't get it to give me just the date.
The date is in dd-mon-yy
format (ex. 14-Jul-14
). What I need is to get it in yyyy
(ex. 2014
). Any assistance would be great.
The code I'm attempting is this, but it doesn't work.
[...]
For I=5 to 5
If Not TransferCol (5) = 0 Then
Worksheets ("Results").Cells.(Row, StartColumn + I) = Worksheets("Program").Cells(RowTransfer, Year (TransferCol (5)))
Exit Do
End If
Next
[....]
Any readable date in Excel is already in a date format. So, to arrive at only the year, we need to customize the date format which can be done through the Format Cells settings. This method will overwrite the dates. If you want to keep the full dates, copy them to another column and format the copied dates.
VBA Date Function – Example #1Step 1: Insert a new module in your Visual Basic Editor. Step 2: Define a sub-procedure to write create and save a macro. Step 3: Define a variable named CurrDate which can hold the value of the current date.
VBA CDATE is a data type conversion function that converts a data type, either text or string, to a date data type. Once we convert the value to date data type, we can play around with date stuff.
It seems to me there are (at least) 2 ways to achieve what you want.
Instead of extracting the year from the source date, you could copy the entire date and format the target cell to only show the year. This way you get to keep the original date information but only show the part you're interested in. Here's an example to copy the date from "Sheet1"/Cell(1,1)
to "Sheet2"/Cell(1,1)
and use NumberFormat
to set the destination cell formatting to only show the 4-digit year part:
Public Sub test1()
Dim rSrc As Range
Dim rDst As Range
Set rSrc = Sheets("Sheet1").Cells(1, 1)
Set rDst = Sheets("Sheet2").Cells(1, 1)
rDst = rSrc
rDst.NumberFormat = "yyyy"
End Sub
Year()
functionWhat you need to be aware of in this case is to ensure the target cell is formatted as an (integer) number. If you format it as a date, then the result will be very wrong, as it will use the year value as a date offset from the year 1901 or thereabouts. The code itself is simple. I'm using the previous example as a basis for this:
Public Sub test2()
Dim rSrc As Range
Dim rDst As Range
Set rSrc = Sheets("Sheet1").Cells(1, 1)
Set rDst = Sheets("Sheet2").Cells(1, 1)
rDst = Year(rSrc)
End Sub
Both examples are simplistic, but I hope they give you the general idea. I'm sure you can adapt them to your requirements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With