VBA code for 2-digit month is very slow

bukimi

Board Regular
Joined
Apr 12, 2017
Messages
105
Office Version
  1. 2019
Platform
  1. Windows
Hello,

I need to add a column, which takes a date and changes it into 2-digit month number (January -> 01, April -> 04, December -> 12, etc.)
It needs not only to be shown/visible as such (like via custom date cell format), but cell contents really need to be these two digits only - stored as text, because otherwise 01 will be automatically converted to 1.

I got a working code like that:
VBA Code:
Sub ChangeDateToText()
Dim DateString As String
Dim c As Range

For Each c In Selection
c.NumberFormat = "@"
DateString = Format(Month(c), "00")
c = DateString
Next c

End Sub

It does the trick, but goes cell by cell, which is really slow and annoying.
Anyone maybe has a more simple way to do that, or can make code above influence whole column at once?
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
How about
VBA Code:
Sub bukimi()
   With Selection
      .NumberFormat = "@"
      .Value = Evaluate(Replace("if(@="""","""",text(month(@),""00""))", "@", .Address))
   End With
End Sub
 
Upvote 0
Solution
Works excellent. Magic :)
Tried breaking that function into steps, but didn't manage to with my current knowledge (mainly the IF part), so I'm taking it as it is.
Thank you!
 
Upvote 0
You're welcome & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,214,579
Messages
6,120,365
Members
448,956
Latest member
Adamsxl

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