Show name of month according to a number in excel

[亡魂溺海] 提交于 2019-12-11 13:29:08

问题


I wonder if there is a way to show the content of a cell container an integer (1-12) as the name of the month (Jan-Dec). If I do it this way:

With Cells("A1")
    .NumberFormatLocal = "MMM"
    .Value = 5
End With

Excel reads the value 5 as the date 5 Jan 1900 as thus returns Jan, while what I want is May.

The thing is I do not want to write a date in cell A1 but only a single integer. When cell A1 is copied by value to another cell or when read, I hope that the value copied/read is 5, not 42129 as if it is 5 May 2015. So conversion is not what I want.

Is there any custom code of formatting and other technique that can help with displaying the values 1-12 as Jan-Dec? Any help is appreciated!


回答1:


If it is mission critical that you bypass the rules of dates and numbers then write 12 conditional formatting rules; one for each number/month name from 1 to 12 and supply a 'literal' custom format mask for each that spells out the abbreviated month.

Sub cf_months()
    Dim m As Long, cnf As String
    With Worksheets("Sheet1")
        With .Range("A1")
            .FormatConditions.Delete
            For m = 12 To 1 Step -1
                cnf = StrConv(Format(DateSerial(2016, m, 1), "mmm"), vbUnicode)
                cnf = Join(Split(cnf, vbNullChar), Chr(92))
                cnf = Chr(91) & Chr(61) & m & Chr(93) & Chr(92) & Left(cnf, Len(cnf) - 1) & Chr(59) & Chr(59) & Chr(59)
                .FormatConditions.Add Type:=xlExpression, Formula1:=Chr(61) & .Address(0, 0) & Chr(61) & m
                .FormatConditions(.FormatConditions.Count).NumberFormat = cnf
                Debug.Print cnf
            Next m
        End With
    End With
End Sub

            



来源:https://stackoverflow.com/questions/36416971/show-name-of-month-according-to-a-number-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!