Search code examples
excelvbaexcel-tableslistobject

get position of activecell in a named table


so i have a table named "Table1" in "sheet1" which range is from A2:B4, if i select B3 that would be Sheet("sheet1").range("Table1").cells(2,2) how would you check thru vba that the activecell in table1 is in cells(2,2)

im doing this because i will be copying/reflecting the value to another named table in another sheet to the same cells(2,2) the table has the same no. of rows and columns, it is exactly the same table just located in another sheet and in a different range


Solution

  • Reference the Same Cell in Another Same Sized Table

    Sub ReferenceSameCell()
        
        Dim wb As Workbook: Set wb = ThisWorkbook
        Dim sws As Worksheet: Set sws = wb.Sheets("Sheet1")
        Dim slo As ListObject: Set slo = sws.ListObjects("Table1")
        Dim srg As Range: Set srg = slo.Range
        
        Dim sCell As Range: Set sCell = ActiveCell
        
        If Not sCell.Worksheet Is sws Then
            MsgBox "Select a cell in worksheet '" & sws.Name & "'.", vbExclamation
            Exit Sub
        End If
        
        If Intersect(sCell, srg) Is Nothing Then
            MsgBox "Select a cell in table '" & slo.Name & "'.", vbExclamation
            Exit Sub
        End If
        
        Dim dws As Worksheet: Set dws = wb.Sheets("Sheet2")
        Dim dlo As ListObject: Set dlo = dws.ListObjects("Table2")
        Dim drg As Range: Set drg = dlo.Range
    
        Dim r As Long: r = sCell.Row - srg.Row + 1
        Dim c As Long: c = sCell.Column - srg.Column + 1
        
        Dim dCell As Range: Set dCell = drg.Cells(r, c)
            
        Debug.Print r, c, sCell.Address, dCell.Address
        
    End Sub