Select Visible Cells Only Using VBA

Visual Basic for Applications (VBA) allows users to simplify every step of the process in Excel. We can benefit from it by automating every single step.

In the example below, we will show how to hide rows and columns in Excel with VBA, and then how to select only the cells that are not visible for further manipulation.

Hide Rows and Columns

For the example, we will use simple data representing every row in which the text is located:

To open the VBA, we will click ALT + F11 on our keyboard, then go to Insert >> Module on the screen that appears:

In the module, we will insert the following code:

This is what it looks like in the module:

This code is pretty simple, and, when executed, it will hide rows 2,3, and 4. If we wanted to do similar things to columns, we would have changed the range to reflect columns, instead of rows, so it would be something like Range(“A:C”) or similar.

We will execute the code by pressing F5 on our keyboard while in the module and our rows will be hidden:

Select Visible Cells Only Using VBA

If we would simply go on and select range: A1:E5 and copy it, we would have an issue because even the hidden cells would be selected.

To resolve this issue, we will create the following code:

Most of the things in the code above should be familiar. We declare one variable, which is r, and with the type range. Then we set it to be equal to our range.

Then we use the SpecialCells function which has two parameters: type as XLCellType and value. In our case, since we already have values (which is our range) we did not define the value.

For the final part of the code, we will copy and paste our range starting with cell A8. When we execute this code (by pressing F5 on the keyboard) this is the result we end up with:

As seen, only the rows that are visible to us were copied.

Tomasz Decker is an Excel specialist, skilled in data analysis and financial modeling.

Posted in vba