首页 > 解决方案 > How do I replace column of numbers in excel with their "th" and "nd" ending?

问题描述

I have a column of numbers in excel that I would like to replace with their two letter ending "th" "nd" as in 13th, or 62nd. How do I do this in excel? I do have a big key that has the number and its ending on a separate sheet.

标签: excelvlookup

解决方案


基数是普通的数字,看起来像:1、2、3、4等。

序数有一个后缀,看起来像:第 1、第 2、第 3、第 4 等。

请注意,在序数形式中,数字实际上是文本,只能用于显示;Excel 将不再考虑它们的数字。

如果一个基数在A1这个公式中将导致它的序数表示......

=IF(OR(--RIGHT(A1,2)={11,12,13}),"th",IFERROR(CHOOSE(RIGHT(A1),"st","nd","rd"),"th"))

上述公式不需要输入数组。只需一个正常的确认就足够了。

为了完整起见,这里提供了一种使用上述令人惊讶的简洁公式作为 UDF 的方法。将以下函数放在 VBA 标准代码模块中...

Function Ordinal(n)
  Ordinal = n & Evaluate("IF(OR(--RIGHT(" & n & ",2)={11,12,13}),""th"",IFERROR(CHOOSE(RIGHT(" & n & "),""st"",""nd"",""rd""),""th""))")
End Function

现在您可以从工作表上的公式中调用它。例如,在单元格中,A1您可以使用以下公式:

=Ordinal(123)

或从 VBA 例程...

Msgbox Ordinal(21)

要获取并保存 VBA 中前 255 个序数的数组,您可以使用以下变体作为函数...

Function Ordinals()
  Ordinals = [ROW(1:255)&IF((--RIGHT(ROW(1:255),2)>10)*(--RIGHT(ROW(1:255),2)<14),"th",IFERROR(CHOOSE(RIGHT(ROW(1:255)),"st","nd","rd"),"th"))]
End Function

现在得到这样的数组......

Sub Test()
  Dim v  
  v = Ordinals  '<-- v is now a 2d array and holds the first 255 ordinals
  MsgBox v(211, 1)
End Sub

推荐阅读