I have the following code that generates an error.
I want to loop through all the tables on the active worksheet and delete the data except for the data on two specified in the code.
Sub Clear_Tables()
Dim tbl As ListObject
For Each tbl In ActiveSheet.ListObjects
If tbl <> "Table_Extracted_Data_Summary" Or tbl <> "Manual_Entries" Then
tbl.DataBodyRange.Rows.Delete
Else
End If
Next tbl
End Sub
The error code is:
Run-time error '91':
Object variable or With block variable not set
I have got the following code working but for some reason if deletes the contents of the 2 tables i want to leave
Sub Clear_Tables()
'PURPOSE: Loop through and apply a change to all Tables in the Active Excel
Sheet
Dim TableToCheck As ListObject
For Each TableToCheck In ActiveSheet.ListObjects
If TableToCheck.Name = "Table_Extracted_Data_Summary" Or
TableToCheck.Name = "Manual_Entries" Then 'Name of Table you do NOT want to
update
If Not (TableToCheck.DataBodyRange Is Nothing) Then
TableToCheck.DataBodyRange.ClearContents
End If
Next TableToCheck
End Sub
Amend your second code to the following. You want tables whose name is NOT A and is NOT B.
Sub Clear_Tables()
'PURPOSE: Loop through and apply a change to all Tables in the Active Excel
Sheet
Dim TableToCheck As ListObject
For Each TableToCheck In ActiveSheet.ListObjects
If TableToCheck.Name <> "Table_Extracted_Data_Summary" And _
TableToCheck.Name <> "Manual_Entries" Then 'Name of Table you do NOT want to update
If Not (TableToCheck.DataBodyRange Is Nothing) Then
TableToCheck.DataBodyRange.ClearContents
End If
End If
Next TableToCheck
End Sub
Or revert from ClearContents to Rows.Delete if appropriate.
Try using the AND operator (an OR might require parentheses):
Sub Clear_Tables()
Dim tbl As ListObject
For Each tbl In ActiveSheet.ListObjects
If tbl <> "Table_Extracted_Data_Summary" And tbl <> "Manual_Entries" Then
tbl.DataBodyRange.Rows.Delete
End If
Next tbl
End Sub
Otherwise your syntaxt seems fine.
I was unable to reproduce your error "91".
Related
When I run this VBA code in macros, it reports
"Run-time error '5941': The requested member of the collection does not exist"
on the highlight line
Sub addColumn()
'
' addColumn
'
'
Application.Templates.LoadBuildingBlocks
Dim myDoc As Document
Set myDoc = Word.ActiveDocument
Dim myTable As Table
With myDoc
iCount = myDoc.Tables.Count
For i = 1 To iCount
Set myTable = myDoc.Tables(i)
myTable.Columns.Add BeforeColumn:=myTable.Columns(6)
Next
End With
End Sub
Could anyone give me some advice?
I wrote this code for dealing with a word.doc which contains lots of tables(606 tables) and other characters. I want to use macros to add a column at the end of each table in the batch. Did I miss something?
If all you want to do is to add a new column after the last column in each table, all you need is:
Sub Demo()
Application.ScreenUpdating = False
Dim Tbl As Table
For Each Tbl In ActiveDocument.Tables
Tbl.Columns.Add
Next
Application.ScreenUpdating = True
End Sub
I have a budget template with tables for each budget category. I have buttons for users to add rows to each budget category with the rows in each category being set as a table so that my total functions work no matter how many rows are added where. But Id like users to also be able to delete rows like if they add too many or if roles change during the time the budget is changed, etc. I don't want users to be able to delete rows such as headers or totals. Protecting the rows doesn't work since the row number can change at any time with new rows being added at any time. The delete selected row code is below as well as my add a row code for the first category which is full time employee salary.
delete selected row - not good since can delete important rows
Sub DeleteSelectedRow()
Rows(ActiveCell.Row).Delete
End Sub
add row to category - good since adds rows to table to keep formulas working
Sub AddConsultant()
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Consultants")
tbl.ListRows.Add
End Sub
Try this:
Sub AddConsultant()
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Consultants")
tbl.ListRows.Add
End Sub
Sub DeleteSelectedRow()
Dim ws As Worksheet
Dim tbl As Range
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Consultants").Range
If InRange(ActiveCell, tbl) Then
Rows(ActiveCell.Row).Delete
Else
MsgBox ("Cannot Delete")
End If
End Sub
Function InRange(Range1 As Range, Range2 As Range) As Boolean
' returns True if Range1 is within Range2
Dim InterSectRange As Range
Set InterSectRange = Application.Intersect(Range1, Range2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
End Function
You can check whether the selection (or part of the selection) range is inside the table of interest.
For example:
Sub AddConsultant()
AddRow "Consultants"
End Sub
Sub RemoveConsultant()
RemoveSelectedRow "Consultants"
End Sub
Sub AddSite()
AddRow "Sites"
End Sub
Sub RemoveSite()
RemoveSelectedRow "Sites"
End Sub
'methods to add/remove rows from the specified table
Sub AddRow(tableName As String)
ActiveSheet.ListObjects(tableName).ListRows.Add
End Sub
Sub RemoveSelectedRow(tableName As String)
Dim rng As Range, ok As Boolean
If TypeName(Selection) = "Range" Then 'is a range selected?
'is the range in the required table?
Set rng = Application.Intersect( _
ActiveSheet.ListObjects(tableName).DataBodyRange, Selection)
If Not rng Is Nothing Then
rng.EntireRow.Delete
ok = True
End If
End If
'didn't delete anything?
If Not ok Then MsgBox "First select one or more rows in " & _
tableName & " table"
End Sub
I am attempting to loop through multiple tables within a single workbook and clear the data on those tables so that new data can be entered. As the row counts, column counts, names, and number of tables can change I was hoping to create a single macro to loop through the tables and perform .DataBodyRange.Delete
Working Code for 1 table called by sheet and object name:
I also found this code on a forum and I believe the IF portion takes into account a table that is already empty so that no error is thrown.
Sub ResetTable()
With ThisWorkbook.Sheets("SheetName").ListObjects("ListObjectName")
If Not .DataBodyRange Is Nothing Then
.DataBodyRange.Delete
End If
End With
End Sub
My attempt at turning this into a more dynamic loop:
The second set of code is failing on With ws .tbl due to a Compile error: Method or data member not found. So I am looking for any help in either fixing the below code or using an entirely different path.
Sub ResetAllTables()
Dim tbl As ListObject
Dim ws As Worksheet
'Loop through each sheet and table in the workbook
For Each ws In ThisWorkbook.Worksheets
For Each tbl In ws.ListObjects
'Do something to all the tables...
With ws.tbl
If Not .DataBodyRange Is Nothing Then
.DataBodyRange.Delete
End If
End With
tbl.ShowTotals = True
Next tbl
Next sht
End Sub
Thanks in advance!
as suggested by BigBen & SRJ,
changing with ws.tbl to just with tbl fixed the issue. also had to fix Next sht to be Next ws
Thanks for the help!
I have three different tables that sends data too another tables in a different sheets when I push a button. However when one or two of the tables are empty I want excel to ignore the empty table/s
I've tried using this code from here but it only adds a new blank row
If WorksheetFunction.CountA(Range("Storningar")) = 1 Then
tblStorning.DataBodyRange.Copy
TargetTblLastRow.Range.PasteSpecial xlPasteValues
End If
Tried this one also but same result:
If tblStorning.DataBodyRange Is Nothing Then
'Do something if there is no data
Else
tblStorning.DataBodyRange.Copy
TargetTblLastRow.Range.PasteSpecial xlPasteValues 'Do something if there is data
End If
This is what the sub looks for one of the tables that sends data from table to the other one without the IF statements
Sub SkickaStorningar()
Dim tblStorning As ListObject
Dim tblStorningOuput As ListObject
Dim TargetTblLastRow As Variant
Set tblStorning = Worksheets("Rapport").ListObjects("Storningar")
Set tblStorningOutput = Worksheets("Storningar").ListObjects("StorningsTabell")
Set TargetTblLastRow = tblStorningOutput.ListRows.Add
tblStorning.DataBodyRange.Copy
TargetTblLastRow.Range.PasteSpecial xlPasteValues
End Sub
When I push the button to send the tables I just want to send the tables that has data and ignore the ones that dont
Thanks for any help
Edit with new info:
You probably have something like this:
Sub SkickaStorningar()
Dim tblStorning As ListObject
Dim tblStorningOuput As ListObject
Dim TargetTblLastRow As Variant
Set tblStorning = Worksheets("Rapport").ListObjects("Storningar")
Set tblStorningOutput = Worksheets("Storningar").ListObjects("StorningsTabell")
Set TargetTblLastRow = tblStorningOutput.ListRows.Add ' Always adds a row
If tblStorning.ListRows.Count > 0 Then
tblStorning.DataBodyRange.Copy
TargetTblLastRow.Range.PasteSpecial xlPasteValues
End If
End Sub
Every time you run this macro, you're adding a new blank row in your target table. You should only add a row if the if statement evaluates TRUE. Like this:
Sub SkickaStorningar()
Dim tblStorning As ListObject
Dim tblStorningOuput As ListObject
Dim TargetTblLastRow As Variant
Set tblStorning = Worksheets("Rapport").ListObjects("Storningar")
Set tblStorningOutput = Worksheets("Storningar").ListObjects("StorningsTabell")
If tblStorning.ListRows.Count > 0 Then
Set TargetTblLastRow = tblStorningOutput.ListRows.Add ' Only execute ListRows.Add if you want to add a row
tblStorning.DataBodyRange.Copy
TargetTblLastRow.Range.PasteSpecial xlPasteValues
End If
End Sub
Try:
Option Explicit
Sub test()
Dim table As ListObject
With ThisWorkbook.Worksheets("Sheet1") '<- Change sheet name if needed
Set table = .ListObjects("tblTest") '<- Change table name
If Not table.DataBodyRange Is Nothing Then
'Code
End If
End With
End Sub
I have a problem which is probably very easy for you to help me solve.
I have two tables: Table1 and Table2. Both tables are in the same worksheet called "Budget".
I want to add a command button / a plus button, that enables a user to add a new row at the bottom of each table.
However, after trying this via the macro record function, I recognized that at some point, the new rows of Table2 are added somewhere in the middle, after having added several new rows to Table1.
Can someone please provide me with a code, that solves this issue and sort of auto-adjusts?
I have never in my life coded something.
Thank you in advance for your help!
Code from recorder:
Sub NEWROW()
'
' NEWROW Makro
'
'
Range("B12:C12").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub
Try this code
Option Explicit
Sub AddRows()
Dim wks As Worksheet
Dim tbl1 As ListObject
Dim tbl2 As ListObject
Set wks = ActiveSheet
Set tbl1 = wks.ListObjects("Table1")
Set tbl2 = wks.ListObjects("Table2")
tbl1.ListRows.Add
tbl2.ListRows.Add
End Sub
Table object is explained here
Update Ok, for an absolute beginner this might be the easiest way to do it.
Sub AddRowTbl1()
Dim wks As Worksheet
Dim tbl As ListObject
Set wks = ActiveSheet
Set tbl = wks.ListObjects("Table1")
tbl.ListRows.Add
End Sub
Sub AddRowTbl2()
Dim wks As Worksheet
Dim tbl As ListObject
Set wks = ActiveSheet
Set tbl = wks.ListObjects("Table2")
tbl.ListRows.Add
End Sub
PS A more advanced user would use a function
Function tblAddRow(tblname As String, wks As Worksheet)
Dim tbl As ListObject
On Error GoTo EH
Set tbl = wks.ListObjects(tblname)
tbl.ListRows.Add
EH:
End Function
Sub Test_tblAdd()
tblAddRow "Table1", ActiveSheet
End Sub