VBA - Replace each date cell in range with its corresponding year

RockandGrohl

Well-known Member
Joined
Aug 1, 2018
Messages
788
Office Version
  1. 2010
Platform
  1. Windows
I'm doing this at the moment, but it's just a messy loop for simpletons:

VBA Code:
    Do Until Cells(ActiveCell.Row, "A").Value = ""
        If ActiveCell.Value <> "" Then
        ActiveCell.Value = Year(ActiveCell.Value)
        ActiveCell.NumberFormat = general
        End If
    ActiveCell.Offset(1, 0).Activate
    Loop

It's just to replace a column (that may or may not have blanks) that contains dates with the year. I can't format because the date will still exist as "04/10/2020" - it needs to just be an integer of "2020"

Is there a better way of doing it? Takes a few seconds to run the loop but I'm sure it can be instant. Thanks.
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
Assuming you are starting at row 2 and the column contains only dates and blank cells, try this with a copy of your data.

VBA Code:
Sub Year_Only()
  With Range("A2", Range("A" & Rows.Count).End(xlUp))
    .NumberFormat = "General"
    .Value = Evaluate(Replace("if(#="""","""",year(#))", "#", .Address))
  End With
End Sub
 
Upvote 0
Thanks, I'll give this a whirl in a couple hours, this is what I wanted to do but couldn't remember the syntax (although the Evaluate is new to me!)
 
Upvote 0
You're welcome. Thanks for the follow-up. :)
 
Upvote 0

Forum statistics

Threads
1,214,919
Messages
6,122,259
Members
449,075
Latest member
staticfluids

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