且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VBA从excel中的筛选表返回第n行数

更新时间:2023-12-01 09:48:16

最简单的方法是特殊单元格。见下文:

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.

然后我们过滤在表格中间的某个地方有几个值...

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

现在,当我们运行上面发布的脚本时,我们的消息框将显示每个未过滤行的绝对行号。结果是1,3,4,5和7。

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.