Find Longest String in an Array Excluding Hidden Rows

ttbuson

Board Regular
Joined
Nov 18, 2011
Messages
80
I have the following code which should find the longest string in an array. I want to modify it to exclude hidden rows, however. Any ideas on how I might do this?

Code:
Dim cell As Range
Dim strLongestCellRef As String
Dim intLongestCellLen As Integer
For Each cell In Sheets("Sheet1").Range("B6:B45")
    If Len(cell) >= intLongestCellLen Then
        intLongestCellLen = Len(cell)
        strLongestCellRef = cell.Value
    End If
Next cell
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
Hi ttbuson,
I see a couple of ways to do this here is two

Code:
Sub findlongest1()
  Dim cell, rng As Range
   Dim strLongestCellRef As String
   Dim intLongestCellLen As Integer
   Set rng = Sheets("Sheet1").Range("B6:B45").SpecialCells(xlCellTypeVisible)
   For Each cell In rng
      If Len(cell) >= intLongestCellLen Then
          intLongestCellLen = Len(cell)
          strLongestCellRef = cell.Value
      End If
  Next cell
End Sub

Sub findlongest2()
    Dim cell As Range
    Dim strLongestCellRef As String
    Dim intLongestCellLen As Integer
    For Each cell In Sheets("Sheet1").Range("B6:B45")
        If cell.Height > 0 Then
            If Len(cell) >= intLongestCellLen Then
                intLongestCellLen = Len(cell)
                strLongestCellRef = cell.Value
            End If
        End If
    Next cell
End Sub

Using ".SpecialCells(xlCellTypeVisible)" is more elegant and is specialty tailored for filtered rows
Using "If cell.Height > 0 Then" is simpler to understand and works but it works on filtered and hidden rows
Cheers
Sergio
 
Last edited:
Upvote 0

Forum statistics

Threads
1,216,110
Messages
6,128,894
Members
449,477
Latest member
panjongshing

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