find table row number from selected cell

2019-05-21 19:08发布

How do I find the row number in a table (Excel 2010) from the selected cell.
I can find the sheet row number from ActiveRow.Row or Selection.Row. But I want to know what row number in the table this is.

4条回答
来,给爷笑一个
2楼-- · 2019-05-21 19:36
    Selection.Row - Selection.ListObject.Range.Row
查看更多
狗以群分
3楼-- · 2019-05-21 19:36

i am not a vba / excel expert but this might do the job:
the answer is a bit late - but i ran into the same problem.
my function returns a listRow object, that is more powerful:

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
查看更多
We Are One
4楼-- · 2019-05-21 19:37

Here's an idea, try getting (active row - first row of table). That will give you the row number from the table.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-05-21 19:49

This might help, assuming that there is only one table in sheet. Otherwise You need to specify the table range.

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
查看更多
登录 后发表回答