快捷搜索:  汽车  科技

日期后一天公式(如何在日期天数后快速加上第n天的英文后缀)

日期后一天公式(如何在日期天数后快速加上第n天的英文后缀)第5 fifth 5th第4 fourth 4th第1 first 1st第2 second 2nd第3 third 3rd

你有没有遇到过这样的场景?

日期后一天公式(如何在日期天数后快速加上第n天的英文后缀)(1)

做了一张带有日期天数的表格,如上表,1-31代表天数,但是因为表格都是数字,看上去过于单调,你希望在天数后面加上英文的天数后缀。

如1号为1st(first缩写),2号为2nd(second缩写),3号为rd(third缩写),其它大部分天数后缀为th。

完整的、正确的后缀列表应该是这样的:

第1 first 1st

第2 second 2nd

第3 third 3rd

第4 fourth 4th

第5 fifth 5th

第6 sixth 6th

第7 seventh 7th

第8 eighth 8th

第9 ninth 9th

第10 tenth 10th

第11 eleventh 11th

第12 twelfth 12th

第13 thirteenth 13th

第14 fourteenth 14th

第15 fifteenth 15th

第16 sixteenth 16th

第17 seventeenth 17th

第18 eighteenth 18th

第19 nineteenth 19th

第20 twentieth 20th

第21 twenty-first 21st

第22 twenty-second 22nd

第23 twenty-third 23rd

第24 twenty-fourth 24th

第25 twenty-fifth 25th

第26 twenty-sixth 26th

第27 twenty-seventh 27th

第28 twenty-eighth 28th

第29 twenty-ninth 29th

第30 thirtieth 30th

第31 thirty-first 31st

你会发现,1-31天中,1、2、3、21、22、23这6天是以st、nd、rd结尾的,而11、12、13和其它天均是以th结尾的。

问题来了,怎么可以实现最快的速度自动给天数后面加上对应的英文(第*天)的后缀呢?

其实,如果只是为了解决这个问题,最简单的方法没有别的,就是手动处理一遍。

为了不改变天数的数据类型,我们可以分别对天数应用自定义格式,让单元格自动“加上”英文后缀。

日期后一天公式(如何在日期天数后快速加上第n天的英文后缀)(2)

然后把做好的格式复制保存下来,以备后用。用的时候,直接复制,没有比这更简单的方法了。

但是,作为Excel控,我们更想实现的是用具体的方法来实现自动添加后缀,通过这个案例能学到一些知识,将来用到其它场景里,这才是这个案例的价值所在。

如前所述,1-31天后面加后缀,其实是分几种情况的,除了11、12、13天以外,如果天数是以1、2、3结尾的,则分别添加st、nd、rd,否则则添加th。

我们用VBA来解决这个问题,来看操作步骤——

步骤1:ALT F11,打开VBE编辑器;

步骤2:添加一个模块,在模块中编写代码如下:

Sub 自动添加英文天后缀()

For c = 2 To 32

If Right(Cells(3 c) 1) = 1 And Cells(3 c) <> 11 Then

Cells(3 c).NumberFormatLocal = "0""st"""

ElseIf Right(Cells(3 c) 1) = 2 And Cells(3 c) <> 12 Then

Cells(3 c).NumberFormatLocal = "0""nd"""

ElseIf Right(Cells(3 c) 1) = 3 And Cells(3 c) <> 13 Then

Cells(3 c).NumberFormatLocal = "0""rd"""

Else

Cells(3 c).NumberFormatLocal = "0""th"""

End If

Next

End Sub

步骤3:执行编写好的程序,一键得到想要的结果。

日期后一天公式(如何在日期天数后快速加上第n天的英文后缀)(3)

总结:

以上代码中使用了VBA中的两个经典语句——For……Next循环遍历语句和If……End If条件判断语句,Cells(3 c).NumberFormatLocal = "0""st"""为自定义格式的代码(可通过录制宏的方式获得)。

通过这个简单的案例,可以看到VBA在解决批量、自动化问题处理上的优势。原本需要手工操作的问题,编写好VBA程序后,一键即可自动执行。

猜您喜欢: