Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA to return nth row number from a filtered table in excel [closed]

Tags:

excel

vba

Can anyone please help me with finding the absolute row number of nth element after filter is applied in an excel table.

For example, I have filter on and have a visible range of data element. Now 20th (nth) row in this filtered range could be 60th row (absolute sense) when no filters are on. Is there a way to find the absolute row number using VBA?

like image 638
crazyfrog Avatar asked Mar 04 '15 13:03

crazyfrog


People also ask

How do you use UsedRange in VBA?

UsedRange can be used to find the last used row in VBA. read more and to reset the used range, etc. Pressing the shortcut Excel keys. read more CTRL+SHIFT+ENTER on a keyboard can be used to extend the selection from an active cell to the last used cell on a worksheet.


1 Answers

Simplest method is special cells. See below:

Sub test()

Dim i As Integer, j As Integer, k As Integer
Dim Report As Worksheet

Set Report = Excel.ActiveSheet ' Store the current worksheet in a variable (always a good idea)
Dim visRng As Range ' Creating a range variable to store our table, excluding any rows that are filtered out.
Set visRng = Report.UsedRange.SpecialCells(xlCellTypeVisible) ' Select only rows within the used range that are visible.

Dim r As Range 
For Each r In visRng.Rows ' Loop through each row in our visible range ...
    MsgBox (r.Row) ' ... and retrieve the "absolute" row number.
Next

End Sub

EDIT

Tom claims this method will not work, but I'm pretty sure it does what you ask. Example:

Here is my original test table--unfiltered so you can see what we're doing. Unfiltered

And then we filter a couple values somewhere in the middle of the table...

Filtered

Now when we run the script I posted above, our message box will show the "absolute" row number for each unfiltered row. Results are 1,3,4,5, and 7.

like image 200
Ross Brasseaux Avatar answered Oct 28 '22 16:10

Ross Brasseaux