Only copy if the table has data - excel

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

Related

Delete a row but button should only work in specified table

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

VBA - Check if data in listobject is filtered

I am trying to develop a custom function to check if the data in a listobject is filtered.
Public Function TestFiltered() As Boolean
Dim rngFilter As Range
Dim r As Long, f As Long
Set rngFilter = ActiveSheet.AutoFilter.Range
r = rngFilter.Rows.Count
f = rngFilter.SpecialCells(xlCellTypeVisible).Count
If r > f Then TestFiltered = True
End Function
However I am getting an error "Object variable not set" in Set rngFilter = ActiveSheet.AutoFilter.Range
All of my sheets will only have one listobject, but perhaps it is safer to somehow change the function to apply the range for the first listobject found in the activesheet?
The idea of multiplying the columns and the rows and comparing them with filterArea.SpecialCells(xlCellTypeVisible).Count is rather interesting. This is what I managed to build on it:
Public Function TestFiltered() As Boolean
Dim filterArea As Range
Dim rowsCount As Long, cellsCount As Long, columnsCount As Long
Set filterArea = ActiveSheet.ListObjects(1).Range
rowsCount = filterArea.rows.Count
columnsCount = filterArea.Columns.Count
cellsCount = filterArea.SpecialCells(xlCellTypeVisible).Count
If (rowsCount * columnsCount) > cellsCount Then
TestFiltered = True
End If
End Function
Here's another approach that tests a specific listobject. It first uses the ShowAutoFilter property of the ListObject to determine whether the AutoFilter is dislayed. If so, it then uses the FilterMode property of the AutoFilter object to determine whether it's in filter mode.
Option Explicit
Sub test()
Dim listObj As ListObject
Set listObj = Worksheets("Sheet2").ListObjects("Table1") 'change the sheet and table names accordingly
If IsListobjectFiltered(listObj) Then
MsgBox listObj.Name & " is filtered", vbInformation
Else
MsgBox listObj.Name & " is not filtered.", vbInformation
End If
End Sub
Function IsListobjectFiltered(ByVal listObj As ListObject) As Boolean
If listObj.ShowAutoFilter Then
If listObj.AutoFilter.FilterMode Then
IsListobjectFiltered = True
Exit Function
End If
End If
IsListobjectFiltered = False
End Function
Try along these lines
Dim i As Long
Dim isFiltered As Boolean
' test if AutoFilter has been turned on in the active sheet
If ActiveSheet.AutoFilterMode Then
' loop through the filters of the AutoFilter
With ActiveSheet.AutoFilter.Filters
For i = 1 To .Count
If .Item(i).On Then
isFiltered = True
Exit For
End If
Next i
End With
End If
This will also work if you are using Tables in Excel. I am using something like this in an If-Then statement to see if the number of rows in the first column matches the number of visible cells in the first column:
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("Table1")
If tbl.ListColumns(1).DataBodyRange.Rows.Count <> tbl.ListColumns(1).DataBodyRange.Rows.SpecialCells(xlCellTypeVisible).Count Then
'Do something if True
End If

Loop through tables and delete data

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".

Excel: Adding new row to bottom of table, when there are two tables (vertically) in the same worksheet

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

Delete all except a range of columns excel VBA

I have hundreds of Columns in excel that I don't need. I have a range that I want to keep.
At the minute I have
Sub DeleteClms ()
Range("A:G,L:O").Delete
End Sub
Is there anyway to make this an opposite, in other languages I would simply put a =!.
I have tried putting <> in but I dont know where/how to put it into my code?
Thanks
There is no Excel or VBA function for the Symetric Difference of the columns that I know of.
Here is a quick VBA function to get there. Usage would be DeleteAllBut Range("A:C,H:Q")
Sub DeleteAllBut(rngToKeep As Range)
Dim ws As Worksheet
Dim rngToDelete As Range
Dim rngColi As Range
'Number of columns used in worksheet
Set ws = rngToKeep.Parent
iCols = ws.UsedRange.Columns.Count
FirstOne = True
For i = 1 To iCols
Set rngColi = Range("A:A").Offset(0, i - 1)
If Intersect(rngToKeep, rngColi) Is Nothing Then
If FirstOne Then
Set rngToDelete = rngColi
FirstOne = False
Else
Set rngToDelete = Union(rngColi, rngToDelete)
End If
End If
Next i
Debug.Print rngToDelete.Address & " was deleted from " & ws.Name
rngToDelete.Delete
End Sub

Resources