excel 从选定单元格查找表格行号

stszievb  于 2023-01-06  发布在  其他
关注(0)|答案(6)|浏览(310)

如何从所选单元格中查找表格(Excel 2010)中的行号。
我可以从ActiveRow.RowSelection.Row中找到工作表行号,但我想知道这是表中的第几行。

fhity93d

fhity93d1#

Selection.Row - Selection.ListObject.Range.Row
btxsgosb

btxsgosb2#

这里有一个想法,尝试获取(活动行-表的第一行)。这将给予你表中的行号。

r7xajy2e

r7xajy2e3#

我不是一个vba / excelMaven,但这可能会做的工作:
答案是有点晚-但我遇到了同样的问题。
我的函数返回一个listRow对象,它的功能更强大:

Sub testit()
    Dim myList As ListObject
    Dim myRow As ListRow
    'some reference to a listObject
    Set myList = ActiveWorkbook.Sheets(1).ListObjects("TableX")
    '
    'test the function
    Set myRow = FirstSelectedListRow(myList)
    '
    'select the row
    myRow.Select
    'get index within sheet
    MsgBox ("sheet row num " & myRow.Range.Row)

   ' get index within list
   MsgBox ("List row index " & myRow.Index)
End Sub
'return ListRow if at least one cell of one row is acitve
'return Nothing otherwise
Function FirstSelectedListRow(list As ListObject) As ListRow
    'default return
    Set FirstSelectedListRow = Nothing
    'declarations
    Dim activeRange As Range
    Dim activeListCells As Range
    Dim indexSelectedRow_Sheet As Long
    Dim indexFirstRowList_Sheet As Long
    Dim indexSelectedRow_List As Long
    'get current selection
    Set activeRange = Selection
    Set activeListCells = Intersect(list.Range, activeRange)
    'no intersection - test
    If activeListCells Is Nothing Then
        Exit Function
    End If
    indexSelectedRow_Sheet = activeRange.Row
    indexFirstRowList_Sheet = list.Range.Row
    indexSelectedRow_List = indexSelectedRow_Sheet - indexFirstRowList_Sheet
    Set FirstSelectedListRow = list.ListRows(indexSelectedRow_List)
End Function
iklwldmw

iklwldmw4#

假设工作表中只有一个表,这可能会有帮助。否则,您需要指定表区域。

Sub FindRowNoInTable()

Dim ObjSheet As Worksheet
Dim startRow, ActiveRow, ActiveCol
Dim ObjList As ListObject
Set ObjSheet = ActiveSheet
ActiveRow = ActiveCell.Row
ActiveCol = ActiveCell.Column
For Each ObjList In ObjSheet.ListObjects
    Application.Goto ObjList.Range
    startRow = ObjList.Range.Row
Next
MsgBox (ActiveRow - startRow)
Cells(ActiveRow, ActiveCol).Select

End Sub
ndh0cuux

ndh0cuux5#

您的范围.行减去您的列表对象.标题行范围.行

n3h0vuf2

n3h0vuf26#

有点晚了,但我在找这个的时候到了这里,所以...
我知道的最简单的方法:

dim MyTable as listobject
    dim MyRow as integer

    ' Here your code or a manual action makes you end up on a random row
    ... Dostuffdostuffbleepbloop ...

    ' Find the row number you landed on within the table (the record number if you will)
    MyRow = MyTable.DataBodyRange().Row

就是这样。
请注意:

  • 这是通过Office 2019完成的
    • DataBodyRange * 后面的括号为空。
  • 行计数器来自***DataBodyRange***,因此不包括标题

希望能帮上忙。

相关问题