Excel VBA - Get name of table based on cell address

后端 未结 2 830
你的背包
你的背包 2021-01-13 06:39

I am using Excel and am looking to get the name of the table based on a cell address (ex A3), this cell will not move. How would I go about stating this in Excel\'s VBA?

相关标签:
2条回答
  • 2021-01-13 07:12

    Attempting to get the name of a ListObject for any cell will cause an error if that cell is not a part of a table.

    Option Explicit
    
    Function CellInTable(thisCell As Range) As String
        Dim tableName As String
        tableName = ""
        On Error Resume Next
        tableName = thisCell.ListObject.Name
        CellInTable = tableName
    End Function
    
    0 讨论(0)
  • 2021-01-13 07:26

    The original question was a bit ambiguous, thus the answer was extended to address all related use-cases.

    One possible alternative is to use the Worksheet Formula shown below entered in any Worksheet Cell (for e.g. $A$3) and then refer it from Excel VBA macro:

    Listing 1. Get Excel Worksheet Name using Cell Formula

    =MID(CELL("filename",A3),FIND("]",CELL("filename",A3))+1,255)
    

    The Formula essentially extracts the Worksheet Name from the Workbook full path.

    Alternatively, you can achieve this in VBA provided that you pass the Range object referring that cell in Worksheet, like in the following demo sample:

    Listing 2. Test Sub to get Excel Worksheet and Table Names for Cell "A3"

    Option Explicit
    
    'Cell "A3" under the test
    Sub GetWorksheetAndTableName()
        Dim myCell As Range
        Set myCell = Range("$A$3")
        Debug.Print "Worksheet Name: " & GetWorksheetName(myCell)
        Debug.Print "Table Name: " & GetTableName(myCell)
    End Sub
    

    Listing 3. Function to get a Worksheet Name for a Cell

    'get Worksheet Name from Range object
    Function GetWorksheetName(CellRange As Range) As String
        On Error Resume Next
        GetWorksheetName = Split(Split(CellRange.Address(External:=True), "]")(1), "!")(0)
    End Function
    

    And, in it's simplest form, the Worksheet Name could be obtained using the following statement (replacing that one in the Function shown in Listing 3):

    Listing 4. Alternative method to get Parent Worksheet Name for Cell/Range object

    GetWorksheetName = CellRange.Parent.Name
    

    In order to get the Table Name for the specified Worksheet Cell refer to the code snippet shown in the following Listing 5:

    Listing 5. Get Table Name for Worksheet Cell

    Function GetTableName(CellRange As Range) As String
        If (CellRange.ListObject Is Nothing) Then
            GetTableName = ""
        Else
            GetTableName = CellRange.ListObject.Name
        End If
    End Function
    

    Hope this may help.

    0 讨论(0)
提交回复
热议问题