5

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?

My plan is to have code that will copy data validations from a row of one table on my Maintenance tab to a single table on each tab of my workbook (minus my "TOC" and "data" tabs). Each tab is a copy of a "TEMPLATE" worksheet (minus the "TOC", "data", & the "TEMPLATE (Maint.)" worksheets). Worksheets "data", "TEMPLATE", and "TEMPLATE (Maint.)" may or may not be hidden.

The code I have in my "Copy_Data_Validations" sub is as follows:

Dim TotalSheets As Integer
Dim p As Integer
Dim iAnswer As VbMsgBoxResult

With Application
    .DisplayAlerts = False
    .ScreenUpdating = False
End With

'
' Move sheet "TOC" to the begining of the workbook.
'
Sheets("TOC").Move Before:=Sheets(1)
'
' Move sheet "data" to be the second sheet in the workbook.
'
Sheets("data").Move Before:=Sheets(2)

iAnswer = MsgBox("You are about to copy data validations!", vbOKCancel + vbExclamation _
+ vbDefaultButton2 + vbMsgBoxSetForeground, "Copying Data Valadations")
For TotalSheets = 1 To Sheets.Count
    For p = 3 To Sheets.Count - 2
'
' If the answer is Yes, then copy data validations from "TEMPLATE (Maint.) to all other.
' sheets minus the "TOC" sheet and the "data" sheet.
'
        If iAnswer = vbYes Then
            If UCase$(Sheets(p).Name) <> "TOC" And UCase$(Sheets(p).Name) <> "data" Then

                ' This chunk of code should copy only the data validations
                ' of "Table1_1" (A4:AO4) from the maintenance tab to all
                ' rows of a single table on each worksheet (minus the
                ' "TOC", "data", & the "TEMPLATE (Maint.)" worksheets.
                ' This is the section of code I am looking for unless
                ' someone has something better they can come up with.

                Selection.PasteSpecial Paste:=xlPasteValidation, _
                Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            End If
'
' If the answer is Cancel, then cancels.
'
        ElseIf iAnswer = vbCancel Then
        ' Add an exit here.
        End If

With Application
    .DisplayAlerts = True
    .ScreenUpdating = True
End With
Ben Rhys-Lewis
  • 3,118
  • 8
  • 34
  • 45
David S.
  • 109
  • 1
  • 3
  • 11
  • `Debug.Print Range("A3").ListObject.Name` *this will error if the cell is not part of a table* – Scott Holtzman Mar 14 '16 at 19:07
  • The question is a bit ambiguous: for example if Cell ($A$3) exists in 3 Worksheets, then which name the VBA function should return? Btw, the solution given below implies passing the Range Object (which implies the Parent Worksheet), not a Cell Address like stated in question. Best regards, – Alexander Bell Mar 14 '16 at 19:23
  • I have updated the question to include some more context so I can get a clearer answer. – David S. Mar 14 '16 at 19:35
  • Your question is still ambiguous, because by referring to Cell($A$3) you already imply the Worksheet it resides in, so you should already have that info as a part of setting code reference to Cell($A$3). Otherwise, put a worksheet function I've shown in every worksheet of interest and refer to it from VBA (though it seems a weird solution). Best regards, – Alexander Bell Mar 14 '16 at 19:47
  • Further clarified, I hope I did better than yesterday's rush job, was feeling ill and had to rush home. Please let me know if anything else is still not explained well enough. – David S. Mar 15 '16 at 13:03
  • Just now realized I accidentally made this post into a duplicate post by adding all of this other information in. This is the duplicate even though the titles are not really related. This is the original post: http://stackoverflow.com/questions/35704246/excel-macro-to-copy-data-validation-only-from-a-template-worksheet-to-several – David S. Mar 15 '16 at 13:23

2 Answers2

10

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
PeterT
  • 8,232
  • 1
  • 17
  • 38
  • 5
    Bonus points for the **[Option Explicit](https://msdn.microsoft.com/en-us/library/y9341s4f.aspx)** statement at the top. –  Mar 14 '16 at 19:18
  • What datatype is "thisCell" referring to above ? – Salih Mar 30 '23 at 10:08
  • @Salih `thisCell` is typed as a `Range`, as indicated in the parameter specification. – PeterT Mar 30 '23 at 14:26
6

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.

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
  • I am not looking for the tab name based on a cell address, I was looking for the name of the table that cell belonged to by inputting a cell address. I have also further given more detail and (hopefully) clarified enough as to what help I am looking for with my code. – David S. Mar 15 '16 at 13:06
  • For your Listing 2, I am looking for the name of the table that the cell is apart of, not getting the worksheet name. Could you update your reply to reflect this please? This would greatly help me. – David S. Apr 12 '16 at 14:00
  • Please refer to my extended answer addressing all your questions. Best regards, – Alexander Bell Apr 12 '16 at 15:56