VBA从excel中的过滤表返回第n行号
任何人都可以请帮我find在Excel表格中应用filter后的第n个元素的绝对行号。
例如,我已经过滤并具有可见范围的数据元素。 在没有滤波器的情况下,此滤波范围内的第20(n)行可能是第60行(绝对量)。 有没有办法find使用VBA的绝对行号?
最简单的方法是特殊的细胞。 见下文:
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
编辑
汤姆声称这种方法是行不通的,但是我很确定这是你所要求的。 例:
这是我原来的testing表 – 没有过滤,所以你可以看到我们在做什么。
然后我们在桌子中间的某个地方过滤一些值
现在,当我们运行上面发布的脚本时,我们的消息框将显示每个未过滤的行的“绝对”行号。 结果是1,3,4,5和7。
作为一个function,我build议
Function RowNum(Target As Range) As Long RowNum = Target.Row End Function
使用通过input一个单元格=RowNum(E9)
。 如果你想让表的行相对于表开始,而你的表从行结束21行开始,只需要从结果中减去它(你可以使用相同的函数来查找表的开始行或行)… eg =rownum(A2)-rownum($A$1)
…介意表头的绝对符号!
如果不喜欢这个function,可以使用SelectionChange事件在消息行中显示所选单元格的行号(可选地取决于表单某处的“debugging标志”)。
非VBA方法将使用CELL公式…例如=CELL("row",A1)
如果在第n个条目之后还有其他隐藏的单元格,@Lopsided所提供的答案将不起作用。 然后他们会被添加到绝对位置。
这将工作,你必须在脚本中自己改变。 改变这个不应该很难。 如果您有任何疑问,请随时询问。 (;
Sub absoluteRowID() Dim RowCount, hiddenRows As Integer 'relative position n n = 5 i = 0 Do While i < n i = i + 1 If ThisWorkbook.Sheets(1).Rows(i).EntireRow.Hidden Then 'if there is a hidden row, position is incremented n = n + 1 End If 'if there is no hidden row, nothing happens Loop MsgBox (i) End Sub
HTH