excel 获取命名表中activecell的位置

kb5ga3dv  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(114)

因此,我在“sheet 1”中有一个名为“Table 1”的表,其范围是从A2到B4,如果我选择B3,则为Sheet("sheet1").range("Table1").cells(2,2),您如何通过vba检查表1中的活动单元格是否在单元格(2,2)中
我这样做是因为我将把值复制/反映到另一个工作表中的另一个命名表的相同单元格(2,2)中。该表具有相同的行数和列数,它是完全相同的表,只是位于另一个工作表中和不同的范围中

50pmv0ei

50pmv0ei1#

你可以这样做:

Sub Tester()
    
    Dim rngT1 As Range, rngT2 As Range, rng As Range, rng2 As Range, addr
    
    Set rngT1 = ActiveSheet.Range("Table1")
    Set rngT2 = ActiveSheet.Range("Table2") 'could be different sheet...

    Set rng = Application.Intersect(Selection, rngT1) 'part of selection within Table1
    
    If Not rng Is Nothing Then   'any selection in table?
        'get the address of the selection *relative* to Table1
        addr = rng.Offset(-rngT1.Row + 1, -rngT1.Column + 1).Address(False, False)
        Debug.Print addr
        Set rng2 = rngT2.Range(addr) 'same relative range in Table2
        rng2.Select 'for example
    End If
    
End Sub
piv4azn7

piv4azn72#

引用另一个大小相同的表格中的相同单元格

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

相关问题