ところで条件付き書式
条件付き書式で変換するというのを検討したのですが、令和元年が本当にガンですね。
これがあるがゆえに条件付き書式は令和元年、令和2年、令和3年と用意しなければなりません。
確かにこれだと日付形式を保持します。しかし現在の使用では令和5年、2023年までは対応できますが、2024年も令和5年になります。
変わっているのは日付、Date関数で設定しても、マクロになるとシリアル値になるところです。(なぜか開始日だけ)
これを手書きでDate関数にしても問題がありません。
時間への対応を忘れない
2021/4/5という値は2021年4月5日5時1分より小さい値です。つまり時間の分だけ足す必要があります。
このため時間まで考えるとシリアル値に+0.999999加算する必要があります。9が7つくらいですね。
ここでexcelの演算誤差、15桁の限界が顔をのぞかせます。シリアル値が5桁なので、7桁程度が安全でしょう。
自動で記録すると、なぜかExcel4Macroが出現します。
Sub SetReiwaFmtConditonActiveCell()
'ActiveCellに日付が入っている場合、令和に変換する条件付き書式を設定します。
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = ActiveSheet
Dim r As Range: Set r = Range(ActiveCell.Address)
Dim xlFormatCondition As FormatCondition, xlFormatConditions As FormatConditions
r.Select
'現在のセルに入っている条件付き書式を削除する Delete Activecell FormatConditions
If r.FormatConditions.Count > 0 Then
For Each xlFormatCondition In r.FormatConditions
xlFormatCondition.Delete
Next
End If
Set xlFormatConditions = r.FormatConditions
r.Select
Set xlFormatCondition = xlFormatConditions.Add(Type:=xlCellValue, Operator:=xlLess, Formula1:="=Date(2019,5,1)")
xlFormatCondition.NumberFormat = "gggee""年""m""月""d""日""(aaa)"
' Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
' ExecuteExcel4Macro "(2,1,""gggee""年""m""月""d""日""(aaa)"")"
' Selection.FormatConditions(1).StopIfTrue = False
xlFormatCondition.SetFirstPriority
xlFormatCondition.StopIfTrue = True
Set xlFormatCondition = xlFormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, _
Formula1:="=43586", Formula2:="=""date(2019,12,31)+0.99999""")
xlFormatCondition.NumberFormat = """令和元年""m""月""d""日(""aaa"")"""
xlFormatCondition.SetFirstPriority
xlFormatCondition.StopIfTrue = True
Set xlFormatCondition = xlFormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, _
Formula1:="=Date(2020,1,1)", Formula2:="=""date(2020,12,31)+0.99999""")
xlFormatCondition.NumberFormat = """令和2年""m""月""d""日(""aaa"")"""
xlFormatCondition.SetFirstPriority
xlFormatCondition.StopIfTrue = True
Set xlFormatCondition = xlFormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, _
Formula1:="=Date(2021,1,1)", Formula2:="=""date(2021,12,31)+0.99999""")
xlFormatCondition.NumberFormat = """令和3年""m""月""d""日(""aaa"")"""
xlFormatCondition.SetFirstPriority
xlFormatCondition.StopIfTrue = True
Set xlFormatCondition = xlFormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, _
Formula1:="=Date(2022,1,1)", Formula2:="=""date(2022,12,31)+0.99999""")
xlFormatCondition.NumberFormat = """令和4年""m""月""d""日(""aaa"")"""
xlFormatCondition.SetFirstPriority
xlFormatCondition.StopIfTrue = True
Set xlFormatCondition = xlFormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, _
Formula1:="=Date(2023,1,1)", Formula2:="=""date(2023,12,31)+0.99999""")
xlFormatCondition.NumberFormat = """令和5年""m""月""d""日(""aaa"")"""
xlFormatCondition.SetFirstPriority
xlFormatCondition.StopIfTrue = True
End Sub