English Ordinal Indicators in Excel using VBA


I often need to determine the ordinal indicator (st/nd/rd/th) associated with a number, especially when I am working with dates. In this post, we will learn to write a simple user defined function in VBA, which will identify the ordinal indicator of an integer. Since the logic is quite straightforward, let us see how we can use the different control structures available in VBA.

A quick refresher on English Ordinal Indicators

The general rule is: numbers ending with 1, 2 and 3, get the ordinal indicators ‘st’, ‘nd’ and ‘rd’ respectively. The exceptions to the previous rule are numbers ending with 11, 12 and 13, which get the ‘th’ indicator.
The rest of the numbers get the ‘th’ indicator.

What are control Structures?

For those of you who are new to programming, in general, any code is executed one line after another. And control structures let you break that rule. They let us jump around unconditionally or conditionally. They even let us keep looping through lines. We will be focussing only on the control structures that let us jump around conditionally, which are generally referred to as Decision Structures.

The two popular decision structures available in VBA are:

  1. If… Then… Else
  2. Select… Case

Follow the links in the list for a detailed account on using these control structures. Although these links are related to VB.NET, and not VBA specifically, almost all the principles apply.

I highly recommend reading about the Select Case statement, as it allows you to implement complex decisions with minimal lines of code. I have used some of these principles in this post, and in the end, I will leave you with a weird way of using the Select Case statement, which I prefer over the If… Then… ElseIf… Else… structure.

Now let us take a look at how we can use the control structures to fetch the ordinal indicator of a number. Notice that I am using the Long data type to accept a number as it will let me work even with very large numbers. The integer data type would suffice for most use cases though.

If… Then… Else

Here is the UDF written using the If… Then… Else structure:

Function OrdinalIndicator(ByVal Number As Long) As String
 
If Number Mod 100 = 11 Or _
    Number Mod 100 = 12 Or _
    Number Mod 100 = 13 Then
    OrdinalIndicator = "th"
    ElseIf Number Mod 10 = 1 Then
        OrdinalIndicator = "st"
    ElseIf Number Mod 10 = 2 Then
        OrdinalIndicator = "st"
    ElseIf Number Mod 10 = 3 Then
        OrdinalIndicator = "rd"
    Else
        OrdinalIndicator = "th"
End If

OrdinalIndicator = Number & OrdinalIndicator

End Function

Select… Case

Here is the UDF written using the Select… Case Structure:

Function OrdinalIndicator(ByVal Number As Long) As String

Select Case Number Mod 100
    Case 11 To 13
        OrdinalIndicator = "th"
    Case Else
        Select Case Number Mod 10
            Case 1
                OrdinalIndicator = "st"
            Case 2
                OrdinalIndicator = "nd"
            Case 3
                OrdinalIndicator = "rd"
            Case Else
                OrdinalIndicator = "th"
        End Select
End Select

OrdinalIndicator = Number & OrdinalIndicator

End Function

Now that you have seen the regular implementation of the Select.. Case statement, let us look at the quirky way I promised earlier. You can pass TRUE as the test expression to the Select statement, and then use Boolean expression beside the Case statements to convert the Select… Case control structure into a compact If… Then… ElseIf… Else structure.

Let me show you what I mean:

Function OrdinalIndicator(ByVal Number As Long) As String

Select Case True
    Case Number Mod 100 = 11, Number Mod 100 = 12, _
         Number Mod 100 = 13
        OrdinalIndicator = "th"
    Case Number Mod 10 = 1
        OrdinalIndicator = "st"
    Case Number Mod 10 = 2
        OrdinalIndicator = "nd"
    Case Number Mod 10 = 3
        OrdinalIndicator = "rd"
    Case Else
        OrdinalIndicator = "th"
End Select

OrdinalIndicator = Number & OrdinalIndicator

End Function

Downloads

I hope that you learnt something new about control structures today. Click on the link below to download a workbook, which contains the three UDFs.

Advertisements

Remove Filters in an Excel Sheet using VBA


Has your data import procedure ever failed due to users applying filters on the data? This happens quite often, especially when you distribute multiple files, which you then stack. Copying filtered data copies only the filtered rows. You end up loosing the hidden rows if users filtered data before saving the workbook. Let us take a look at how to remove filters in an Excel sheet using VBA.

Before we dive into how to remove filters, let us briefly take a look at the types of filtering capability Excel offers. Filtering in Excel comes in two flavours:

Auto filter adds dropdown buttons to the columns, which offer you a variety of filtering and sorting options through an intuitive graphical interface. Advanced Filter on the other hand, lets you specify your filtering criteria in a range of cells.

Auto Filter is easy to spot visually; the dropdowns are hard to miss. However, Advanced Filter is a harder to spot. In both cases, if some of the Row Numbers to the left of a sheet appear blue instead of the regular black colour, filters have been applied on that sheet.

Mastering both these skills are essential for anybody who uses Excel at their workplace. There are a multitude of resources on the internet on these topics. I recommend you familiarise yourself with filtering data in Excel.

The ShowAllData method of the Worksheet object lets you remove any filters that were applied on the data. However, it throws a runtime error when filters have not been applied. One could simply supress the error and call it a day, but I’d loose sleep over resorting to such cowardice. Let us try to figure out a legitimate way of finding whether or not filters have been applied on a sheet.

The FilterMode property of the Worksheet object gets set to TRUE, when filters are applied either as Auto Filters or Advanced Filters. This is a Read-Only property. It can be used to check whether any filters are applied, before using the ShowAllData method. This will help us ensure a runtime error is not triggered when calling the ShowAllData method.

If you are interested in removing the Auto Filter Dropdown buttons as well, which is how I prefer it, you can use the AutoFilterMode property to turn it off. This property is not a Read-Only property, which means you can set it to TRUE to activate AutoFilters and vice versa.

Wrapping this all up, here is a Sub that I use very frequently, which you can use in your projects:

Sub RemoveFilters(ByRef WhichSheet As Worksheet)

'If data is filtered either using AutoFilters or Advanced Filters
'Show all the data
If WhichSheet.FilterMode Then WhichSheet.ShowAllData
'Hide the AutoFilter DropDown Buttons
If WhichSheet.AutoFilterMode Then WhichSheet.AutoFilterMode = False

End Sub

Just pass a Worksheet to the above sub to remove filters without encountering a runtime error.

Note that having Excel Tables, also known List Objects in VBA, in the worksheet could throw these properties off, especially when the active cell is in a Table. If you are using Excel Tables, and I highly recommend that you do, you can deal with filters applied to a table specifically. We will reserve that discussion for another day.


Downloads

Click the link below to download a workbook with the above code. It also has a cover macro on removing filters in the active sheet.

Remove Filters V1.01.xlsb
Remove Filters V1.01.xlsb

Further Reading

  • Advanced filters come in handy when you have to apply a rather complex filter criteria repeatedly. It is also easy to filter data using VBA if you create an appropriate criteria range. Coding the application of AutoFilters is rather cumbersome. Here is an introduction to using AutoFilters in Excel:

Removing non-printing characters from text in Excel using VBA


Have you ever encountered a perfectly constructed MATCH or a VLOOKUP function failing for no apparent reason? Have you had VBA tell you that a file does not exist even though it does? You may have non-printing characters to blame. There are notorious space-like characters that are invisible to the naked eye, which sneak in when you are importing data from Web Pages, Word Documents or PDFs. In this post we will learn more about these characters and how to remove them from your data.

Continue reading “Removing non-printing characters from text in Excel using VBA”

Is the WorksheetFunction property necessary in Excel VBA?


Excel’s Application object’s WorksheetFunction property is a container for Microsoft Excel worksheet function. This property returns a WorksheetFunction object that allows VBA access to the rich set of functions that are built into Excel. While VBA has some generic functions of its own, Excel’s set is much bigger, and more suited for (you guessed it) Excel. As soon as you type in the dot after WorksheetFunction, you will see a list of Excel functions that you can use in your VBA code. But do you really need the WorksheetFunction object?

Continue reading “Is the WorksheetFunction property necessary in Excel VBA?”

First Class Progress Bar for all your Macros


I believe I owe you an explanation; about this post’s title. At first, you might think I am a pompous prick, branding my work myself as First Class. This Progress Bar was my first project after I learned how to set up class modules: hence the name. The progress bar that I developed earlier, is one of my most visited posts, and I thought I have to reward my readers with a progress bar that is much easier to use.

Continue reading “First Class Progress Bar for all your Macros”

How to deal with the Numbers Stored As Text Error in Excel?


How many times have you encountered the “Numbers Stored as text” error in your data sets? It interferes with your LOOKUP and MATCH functions, and arithmetic calculations. Excel has a Convert to Number functionality to help with this situation, but it could be a lot better. You have to deal with your columns one at a time, sometimes one cell at a time. Also, I noticed that if the dataset is huge, excel takes a lot of time to push through; occasionally, it is so slow that you can see the cells getting updated one by one.

Continue reading “How to deal with the Numbers Stored As Text Error in Excel?”

Magically Select All The Used Areas In A Sheet using VBA


I recently published a post about automatically formatting a table in Excel using VBA. That got me thinking, how awesome it would be, if we could format all the tables in a sheet, with a single click. For that idea to work, we need to get all the used areas in a worksheet; and then use the Areas Collection to loop through the tables. We can access the Areas Collection through the Areas property of the Range object.

Continue reading “Magically Select All The Used Areas In A Sheet using VBA”

Magically Format Tables in Excel using VBA


Excel Tables make analyzing data, a breeze. It surprises me that it is not used as often as it should. It automatically “includes” new data you add to your spreadsheets, it automatically drags down formulas for you, it automatically formats the tables for you. In addition to that, you can use structured references that make your formulas tractable without having to name each range. You can also link an Excel Table to your PowerPivot Model. For a comprehensive, yet concise list of stuff excel tables can do, I recommend reading through this page.

Continue reading “Magically Format Tables in Excel using VBA”

To Err is Excel, Handle your Errors with grace


Error handling is an important aspect of programming in VBA, especially if you are writing macros for other users. Unfortunately, many users ignore it completely. Visual Basics is an amazing programming language, but it lags far behind in the error handling department. All we have is the On Error”, “Goto” and the “Resume” statements. These statements allow only a few error handling structures, and each of the structures has its own set of expert proponents. In this post, I am going to share with you, a little block of code that I use to handle errors in all my spreadsheet applications; and hopefully offer a fresh perspective.

Continue reading “To Err is Excel, Handle your Errors with grace”