feedburner
Enter your email address:

Delivered by FeedBurner

feedburner count
Showing posts with label Visual Basic. Show all posts
Showing posts with label Visual Basic. Show all posts

Convert Numbers into String with Ordinal Suffix

Labels:

The VBA code below allows you to represent a numeric value as its ordinal position in a set. The VBA function takes a numeric value and returns the number with the correct ordinal suffix as a string.
For example:

  • strOrdinal(1)
returns “1st”, and
  • strOrdinal(42)
returns “42nd”
The strOrdinal function uses the Mod operator to get the last two digits of the number. For all values between 11 and 19, apply “th” as the suffix. Otherwise, it again uses Mod operator to get the last digit of the number and apply the following rules:
  • Numbers that end in 1, use “st”
  • Numbers that end in 2, use "nd"
  • Numbers that end in 3, use "rd"
  • Otherwise, use "th"

Here’s the code for the function that converts numbers into a string with ordinal suffix:

Public Function strOrdinal(lngVal As Long) As String 
  Dim intDigit As Integer 
  Dim intTeen As Integer 
  Dim strSuffix As String 
  ' Check for the "teens" first 
  intTeen = lngVal Mod 100 
  If intTeen >= 11 And intTeen <= 19 Then  
    ' if teens, use "th" 
    strSuffix = "th" 
  Else 
    ' Get the last digit 
    intDigit = lngVal Mod 10 
    Select Case intDigit 
      Case 1 
        strSuffix = "st" 
      Case 2 
        strSuffix = "nd" 
      Case 3 
        strSuffix = "rd"  
      Case Else 
        strSuffix = "th" 
      End Select 
    End If 
    strOrdinal = lngVal & strSuffix 
End Function

Read More...