Sharing: Getting Visible Cells on Protected Sheet, VBA

Jeffrey Mahoney

Well-known Member
Joined
May 31, 2015
Messages
3,158
Office Version
  1. 365
Platform
  1. Windows
I haven't seen an answer to this issue yet so I'm posting my solution. I have no question, but if someone has a better option, please let me know.

Problem: Getting a range of visible cells using the SpecialCells function gives an error on protected sheets. The option of unlocking the sheet is sometimes not an option.
VBA Code:
'Normal returns a range if columns A through G are visible
Dim Sht as Worksheet
Dim R as Range
Set R = Intersect(Sht.Cells.SpecialCells(xlVisible), Sht.Range("A1:G1"))

Instead, I created a UDF to look at all the columns' visibility. The function below took my computer .07 seconds to return a range of 15 visible columns.
VBA Code:
Sub test()
  Dim t As Double

  t = Timer
 
  Debug.Print GetVisibleColumns(ActiveSheet).Address
  Debug.Print Timer - t

End Sub

Function GetVisibleColumns(Sht As Worksheet) As Range

  Dim u As Range
  Dim Cel As Range
 
  For Each Cel In Sht.Range("1:1")
    If Cel.EntireColumn.Hidden = False Then
      If Not u Is Nothing Then
        Set u = Union(u, Cel.EntireColumn)
      Else
        Set u = Cel.EntireColumn
      End If
    End If
  Next Cel
  If Not u Is Nothing Then Set GetVisibleColumns = u
 
End Function
 

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.

Forum statistics

Threads
1,223,984
Messages
6,175,786
Members
452,670
Latest member
nogarth

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top