Change a value of a cell using a macro in an excel report
I may need to change a value of a cell to a specific value that I want, it is the “replace” function in macro so you may wondering “why to use it if I can do it without coding ?”. The macro is quicker but the best answer will be, for instance, you want to change cells with a specific date into “next coming month”, well the “replace” function will not be able to do it.
When I use the macro ?
Usually I used it to change a date value to something like “next month”.
How to create the macro ?
Read How to create, edit, hide and select a macro in an excel report
How to create the button to associate it with the macro ?
Read How to create a button and associated it to a macro in an excel report
How is/are the macro(s) ?
Copy the code below and paste it into your macro. You will see my comments in green if exist so follow the help to adapt to your need.
Based on cell range, for instance, to change a date value to a specific word:
Sub test() Dim MyRange As Range Dim MyCell As Range ' changethe range Set MyRange = Range("B2:B20") For Each MyCell In MyRange.Cells If VarType(MyCell) = vbDate Then ' changedate if you are searching something else If MyCell >= Int(DateSerial(Year(Date), Month(Date), 1)) Then ' change month by the new word you want to replace MyCell = "month" End If End If Next MyCell End Sub
Based on column range, for instance, to change a word by another word:
Sub test() Dim Rang As Range Dim Cell As Range With ActiveSheet ' changeA:B by your column range Set Rang = Intersect(.Columns("A:B"), .UsedRange) End With For Each Cell In Rang ' change month by the word you are searching If Cell.Value >= "month" Then ' change out of date by the new word you want to replace Cell.Value = "out of date" End If Next Cell End Sub
Interesting Topics
-
Be successfully certified ITIL 4 Managing Professional
Study, study and study, I couldn’t be successfully certified without studying it, if you are interested...
-
Be successfully certified ITIL 4 Strategic Leader
With my ITIL 4 Managing Professional certification (ITIL MP) in the pocket, it was time to go for the...
-
Hide visual and change background color based on selection
Some small tricks to customize the background colour of a text box...
-
Stacked and clustered column chart or double stacked column chart
In excel, I use a lot the combination of clustered and stacked chart...