VBA Creating Named Tables in multiple sheets in new workbook

Davavo

Board Regular
Joined
Aug 3, 2019
Messages
82
Hi, i have some code that
a) filters data from the table in one sheet into a group of new sheets named by the filter value
b) creates a new workbook from these sheets

The script does the above. The additional code has no effect that i can see. It doesnt stop it working, it just doesnt do anything.

I am trying to stick some code in between that turns the data on the sheets into tables before it copies them to a separate workbook (and preserve the tables of course).
I am also trying to name the table according to the sheet name and then add the total rows.
I have the code for adding a table, naming it (not according to the sheet name) and adding the total rows working on a one sheet version. But on this multi sheet method i cant get it to do anything.

I am doing it while the sheets are still in the original workbook because i figure it might be easier than trying to turn the data into tables when it is a separate workbook, but if it is easier, i have no preference.


I will paste the code section followed by the whole code including the secretion, which i have marked.

I would really appreciate someone showing me how to do this. A little explanation would also be great as I am trying my best to figure out how it actually works.

Code:
'----------------------------------------------------------------------------------------------------------------------------------------------------------------------'Start of code section that does not work


'create named tables on each sheet with total rows


For Each ws In ThisWorkbook.Worksheets
        Select Case ws.Name
            Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to be worked on
            Case Else
            
                
                With Workbooks("Expenses.xlsm")
                                                                        
                                                                       
                    LastRow = ws.Range("M" & Rows.Count).End(xlUp).Row
                    
                    Range("A1:M20").Select
                    
                    'Range("A" & Lastrow, "M" & Lastrow).Select
                    
                    .ListObjects.Add(1, .Cells(1).CurrentRegion, , 1).Name = "TCCRecords" & ActiveSheet.Name
                    Columns("K").ColumnWidth = 25
                    


Set listob = ws.ListObjects(1)
                    
                    listob.ShowTotals = True
                                    
                                    
                                With ws.ListObjects("TCCRecords" & ActiveSheet.Name)
                                    .ListColumns("Value Excluding VAT £").TotalsCalculation = xlTotalsCalculationSum
                                    .ListColumns("VAT Value £").TotalsCalculation = xlTotalsCalculationSum
                                    .ListColumns("Total  Value £").TotalsCalculation = xlTotalsCalculationSum
                                    .ListColumns("Cost Centre").TotalsCalculation = xlTotalsCalculationNone
                                    
                                    Range("A1").Select
                                
                                
                                End With


                End With
        End Select


    Next
    
'end of code section that does not work
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Full code ......


Code:
Sub NewNamedWorkbook()

Dim NewName As String
Dim LastRow As Long
Dim strFile As String
Dim listob As ListObject
       
    If MsgBox("Filter range to a new workbook?" _
    , vbYesNo, "NewCopy") = vbNo Then Exit Sub
    
    
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    
    
With Application
               
retry:
    
 'Input box to name new file
NewName = InputBox("Please Specify the name of your new workbook")
            
    
        If StrPtr(NewName) = 0 Then
        
            MsgBox ("User canceled!")
            GoTo reset
                
        Else
        End If
    
        'VBA Check if File Exists
        
        strFile = ThisWorkbook.Path & "\" & NewName & ".xlsx"
    
        If FileExists(strFile) Then
            'File Exists
            MsgBox "The filename you have chosen already exists, please choose a unique filename"
            
        GoTo retry
        
        Else
        End If
End With




Set NewBook = Workbooks.Add


With NewBook


        .title = NewName 'name of new workbook
        .Subject = "Expenses In WorkSheets arranged by Cost Centre or Task Code"
        '       Save it with the NewName and in the same directory as the tool
        .SaveAs ThisWorkbook.Path & "\" & NewName & ".xlsx"


End With
   
Call columntosheets 'filter column and copy to separate sheets


'----------------------------------------------------------------------------------------------------------------------------------------------------------------------
'Start of code section that does not work


'create named tables on each sheet with total rows


For Each ws In ThisWorkbook.Worksheets
        Select Case ws.Name
            Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to be worked on
            Case Else
            
                
                With Workbooks("Expenses.xlsm")
                                                                        
                                                                       
                    LastRow = ws.Range("M" & Rows.Count).End(xlUp).Row
                    
                    Range("A1:M20").Select
                    
                    'Range("A" & Lastrow, "M" & Lastrow).Select
                    
                    .ListObjects.Add(1, .Cells(1).CurrentRegion, , 1).Name = "TCCRecords" & ActiveSheet.Name
                    Columns("K").ColumnWidth = 25
                    


Set listob = ws.ListObjects(1)
                    
                    listob.ShowTotals = True
                                    
                                    
                                With ws.ListObjects("TCCRecords" & ActiveSheet.Name)
                                    .ListColumns("Value Excluding VAT £").TotalsCalculation = xlTotalsCalculationSum
                                    .ListColumns("VAT Value £").TotalsCalculation = xlTotalsCalculationSum
                                    .ListColumns("Total  Value £").TotalsCalculation = xlTotalsCalculationSum
                                    .ListColumns("Cost Centre").TotalsCalculation = xlTotalsCalculationNone
                                    
                                    Range("A1").Select
                                
                                
                                End With


                End With
        End Select


    Next
    
'end of code section that does not work
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------




    For Each ws In ThisWorkbook.Worksheets
        Select Case ws.Name
            Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to copy
            Case Else
            'copy here
                
                With Workbooks("Expenses.xlsm")
                    'ws.Copy After:=.Sheets(.Sheets.Count) 'copys after last sheet
                
                    ws.Copy Before:=Workbooks(NewName & ".xlsx").Sheets(1)
                
                End With
        End Select


    Next




Workbooks(NewName & ".xlsx").Activate


Application.DisplayAlerts = False
Sheets("Sheet1").Delete
Application.DisplayAlerts = True




'delete the sheets from the main workbook


    For Each ws In ThisWorkbook.Worksheets
            Select Case ws.Name
                Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to copy
                Case Else
                'copy here
                    
                    With Workbooks("Expenses.xlsm")
                        'ws.Copy After:=.Sheets(.Sheets.Count) 'copys after last sheet
                        Application.DisplayAlerts = False
                        ws.Delete
                        Application.DisplayAlerts = True


                    End With
            End Select
    
        Next




  
    Exit Sub


reset:
'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True






End Sub
 
Last edited:

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
Try
Code:
   For Each ws In ThisWorkbook.Worksheets
      Select Case ws.Name
         Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to be worked on
         Case Else
            ws.ListObjects.Add(1, ws.Cells(1).CurrentRegion, , 1).Name = "TCCRecords" & ActiveSheet.Name
            With ws.ListObjects("TCCRecords" & ActiveSheet.Name)
               ws.Columns("K").ColumnWidth = 25
               .ShowTotals = True
               .ListColumns("Value Excluding VAT £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("VAT Value £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("Total  Value £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("Cost Centre").TotalsCalculation = xlTotalsCalculationNone
            End With
      End Select
   Next
 
Upvote 0
Hello again Fluff,
thanks for your response.

It is doing the same thing. i.e. nothing.

I wonder if the called sub has something to do with it?

here is the code for that...

Code:
Const sname As String = "CCRead" 'change to whatever starting sheetConst s As String = "M" 'change to whatever criterion column


Sub columntosheets()


Dim wb As Workbook


Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set wb = ThisWorkbook


Set d = CreateObject("scripting.dictionary")


With wb.Sheets(sname)
    rws = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
    cls = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
    cc = .Columns(s).Column
End With


For Each sh In Worksheets
    d(sh.Name) = 1
Next sh


Application.ScreenUpdating = False
With wb.Sheets.Add(after:=wb.Sheets(sname))
wb.Sheets(sname).Cells(1).Resize(rws, cls).Copy .Cells(1)
.Cells(1).Resize(rws, cls).Sort .Cells(cc), 2, Header:=xlYes
a = .Cells(cc).Resize(rws + 1, 1)
p = 2
For i = 2 To rws + 1
    If a(i, 1) <> a(p, 1) Then
        If d(a(p, 1)) <> 1 Then
            Sheets.Add.Name = a(p, 1)
            .Cells(1).Resize(, cls).Copy Cells(1)
            .Cells(p, 1).Resize(i - p, cls).Copy Cells(2, 1)
        End If
        p = i
    End If
Next i
Application.DisplayAlerts = False
    .Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End With
wb.Sheets(sname).Activate


End Sub

Other symptoms that might provide a clue.

I have a little bit of code in the sheet module that hides the sheet when it is deactivated.
This weirdly stops working after running this code. Until i run one of the other macros that work on the sheet, it stays hidden.
Also, Application.Calculation = xlCalculationAutomatic is at the end of the macro, but it is staying on manual.

:confused:
 
Upvote 0
Is the code in the same workbook as the data you want to turn into tables?
Also does all the data start in A1?
 
Upvote 0
Is the code in the same workbook as the data you want to turn into tables?
Also does all the data start in A1?

Hi, no the code is not in the sheet module. Should it be?

The only code in the sheet module is
Code:
Private Sub Worksheet_Deactivate() Me.Visible = False 'hides the worksheet
End Sub

which isnt really necessary tbh

The table starts at A1:M1 with a header.
A2:M2 is blank.
The data is read in by macro and starts at A3:M3.
 
Upvote 0
Hi, no the code is not in the sheet module. Should it be?
No it doesn't need to be in a sheet module, but is it in the same workbook as the data to be changed?
A2:M2 is blank.
This will be (part of) the problem. Do you have to have a blank row? If you want it converted to a table it's best not to have any blank rows in the data.
 
Upvote 0
ok, sorry, i miss read.

Yes, same workbook at teh poitn when this macro is working. The macro creates new sheets from a filtered column, then copies those new sheets to a new workbook. I am trying to create the table on the sheets before they are copied.

The data source table has spaces. The main sheet has a space at row 2. But the sheets that are created with this macro have no space. Its just the header and data.
 
Upvote 0
In that case try
Code:
   For Each ws In Workbooks(NewName & ".xlsx").Worksheets
      Select Case ws.Name
         Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to be worked on
         Case Else
            ws.ListObjects.Add(1, ws.Cells(1).CurrentRegion, , 1).Name = "TCCRecords" & ActiveSheet.Name
            With ws.ListObjects("TCCRecords" & ActiveSheet.Name)
               ws.Columns("K").ColumnWidth = 25
               .ShowTotals = True
               .ListColumns("Value Excluding VAT £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("VAT Value £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("Total  Value £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("Cost Centre").TotalsCalculation = xlTotalsCalculationNone
            End With
      End Select
   Next
This needs to go after the sheets have been added to the new workbook
 
Upvote 0
Yes!
Almost there!

Its creating the tables in the new workbook. The only thing is that the tables are named after the first worksheet only... i.e. sheetname, sheetname_1, sheetname_2

Is this because of the code
Code:
1).Name = "TCCRecords" & ActiveSheet.Name
and the activesheet doesn't change?

I stuck in
Code:
ws.Activate
and it worked!

Code:
For Each ws In Workbooks(NewName & ".xlsx").Worksheets      Select Case ws.Name
         Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to be worked on
         Case Else
         ws.Activate
            ws.ListObjects.Add(1, ws.Cells(1).CurrentRegion, , 1).Name = "TCCRecords" & ActiveSheet.Name
            With ws.ListObjects("TCCRecords" & ActiveSheet.Name)
               ws.Columns("K").ColumnWidth = 15
               .ShowTotals = True
               .ListColumns("Value Excluding VAT £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("VAT Value £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("Total  Value £").TotalsCalculation = xlTotalsCalculationSum
               .ListColumns("Cost Centre").TotalsCalculation = xlTotalsCalculationNone
            End With
      End Select
   Next

Life saver once again Fluff. Thanks a million!
 
Upvote 0
You're welcome & thanks for the feedback

Missed the Activesheet part rather than activateing the sheet you could just replace
Code:
ActiveSheet.Name
with
Code:
ws.Name
in both places.
 
Upvote 0

Forum statistics

Threads
1,224,822
Messages
6,181,165
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top