Delete Last Row in Table vba - excel

Hi have used the below code to remove the last row of data from a table. The code works ok in isolation but when run as part of a larger set of code it does not remove the last row. Any ideas on what is causing this and solution would be appreciated.
Sub TrimJrnl()
Dim wsR2 As Worksheet
Set wsR2 = ThisWorkbook.Sheets("Journal")
lastrow = wsR2.ListObjects("xJrnl").Range.rows.Count
rows(lastrow).Delete
End Sub

You need to count the rows of ListObjects("xJrnl").DataBodyRange so you know how many data rows are there (except header and summary rows).
You can access those data rows by ListObjects("xJrnl").ListRows(LastRow) and .Delete them.
Like Below:
Option Explicit
Public Sub TrimJrnl()
Dim wsR2 As Worksheet
Set wsR2 = ThisWorkbook.Sheets("Journal")
Dim LastRow As Long
LastRow = wsR2.ListObjects("xJrnl").DataBodyRange.Rows.Count
wsR2.ListObjects("xJrnl").ListRows(LastRow).Delete
End Sub
A nice guide how to work with tables: The VBA Guide To ListObject Excel Tables

Related

Delete rows from list

I would like to write a macro to delete all records from my Excel table, except for the first row (as that's where several formulas as stored. The number of records in my table is changing, so it needs to be flexible. I am currently using the following code:
Sheets("5. Informatieproducten Index").Select
Range("A6").Select
Range(Selection, Selection.End(xlDown)).Delete
Please help!.
Tnx
By detecting the last row and last column of your data :
LastRow = Cells.SpecialCells(xlCellTypeLastCell).Row
LastCol = Range("A2").CurrentRegion.Columns.Count
Range(Cells(2,1),Cells(LastRow,LastCol)).Clear
You can do it as follows:
Sheets("5. Informatieproducten Index").Range("A2:XFD1048576").Delete
This deletes the information of all cells, from A2 (just under the first row) to XFD1048576 (which is the most right-bottom cell possible).
There are so many diferent ways to do that. Before all you need to declare a variable to always look for the last row of you table. Then the next step is to look all the lines below the first row of your table and the last row that you previously declared. Note that you can clean or delete the rows. Obs: clean is the method that you keeps the format of your cell and table. Delete is the method that you remove all the formats.
Sub deleteRows()
Dim wb As Workbook
Dim ws As Worksheet
Dim lastRow As Integer
Dim firstRow As Integer
Set wb = ThisWorkbook
Set ws = wb.Worksheets("5. Informatieproducten Index")
'first Row of your table - you can do diferents things to take always the first row of your table
firstRow = ws.Range("A5").Row
'you need to take care if there is any blank cell in the interval
lastRow = ws.Range("A5").End(xlDown).Row
ws.Range("A" & firstRow & ":A9" & lastRow).EntireRow.Delete
End Sub

Adding a new row with data to excel sheet using VBA

I am adding a new row to a table but want to then add the data to that row that I just added. I am thinking something like this, but not sure how to add each columns data to that new row. My table has 4 columns named "store" "emp#" "date" & "amt". I have specific data that I will put in each column. I simplified the code, as there is a whole lot more to the macro, but just stuck on this part. Thank you for you help.
Dim rt_ws As Worksheet
Dim rt_tbl As ListObject
Set rt_ws = ThisWorkbook.Worksheets("RT Clock Hours")
Set rt_tbl = rt_ws.ListObjects("rt_hours")
With rt_table.ListRows.Add
. `this is where I am not sure what to do`
.
.
End Sub
Try this code
Sub Test()
Dim ws As Worksheet, tbl As ListObject
Set ws = ThisWorkbook.Worksheets("RT Clock Hours")
Set tbl = ws.ListObjects("rt_hours")
With tbl.ListRows.Add
.Range = Array("Store1", "1530", "05/03/2020", "Amt1")
End With
End Sub

Delete Duplicated with Right function

I'm looking for a macro to delete duplicates in a column, regarding their last value
e.g.
DES_FFAs_556
asda_FRF_556
Because 556 is same, it should be deleted.
right now im getting the last 4 digits of each cell but i dont know how to remove duplicates with it
Sub duplicates()
Dim i As Long
Dim res As String
Dim WB As Workbook
Dim WS As Worksheet
Dim total As Long
Set WB = Workbooks("MQB37W - SW Architecture Matrix_Nw")
Set WS = WB.Sheets("SW Architecture Main - In...")
With WS
total = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 4 To total
res = Right(Cells(i, "A").Value, 4)
WS.Range("A4:total").RemoveDuplicates Columns:=1, Header:=xlNo
Next
End With
End Sub
You do not need VBA for this. You can just use code from this tutorial in a new column and than based on that column you can filter, conditional format or delete rows. If you would like to indicate only rows after the first occurrence you can use COUNTIF. Ofcourse if you need VBA for something else you can apply the same logic I described above inside the VBA code.

Copying a filtered data from a table set and paste it on the next empty row of another sheet

I tried to copy a set of filtered data from the worksheet "PEP" (Filter: Emetteurs, in column 18) and paste it in the next empty row in the worksheet"Sanctions". I found this text code online and add the section NextRow in order to paste it on the next Empty Row in the "Sanctions" Worksheet. I just started using VBA not long ago, so I tried to use codes online however in this case, I think the problem here is that I cannot define the value of range. I tried to look it up online but no result. Thank you in advance for all your help!
Dim k,j,i As Interger
ActiveWorkbook.Sheets("Sanctions").Select
NextRow=Cells(Range("A"&Rows.Count).End(xlUp).Row+1,1
k=1
With sheets("PEP")
T=.Range("A1:AS"&.Cells(Rows.Count,1).End(xlUp).Row)
.Rows(1).Copy Sheets("Sanctions").Range("NextRow")
End With
For i=2 To UBound(T,1)
If T(i,18)="Emetteurs" Then
k=k+1
For j =1 to UBound(T,2)
T(k,j)=T(i,j)
Next j
End If
Next i
With Sheets("Sanctions")
Application.ScreenUpdating=False
.Range("NextRow").Resiwe(k,UBound(T,2))=T.Offset(1)
.Columns.AutoFit
Application.ScreenUpdating=True
End With
End Sub
And if possible I would also like to find a solution to remove the header once I do the Copy-Paste process.
Read the code's comments and adjust it to fit your needs.
Some things to begin:
Use option explicit so you don't have unexpected behavior with undefined variables
Always indent your code (see www.rubberduckvba.com a free tool that helps you with that)
Try to separate your logic defining variables and the reusing them
EDIT: Some reviews to your code:
As mentioned by #Pᴇʜ you need to declare each of your variables types.
This:
Dim k,j,i As Interger
is the same as declaring:
Dim k As Variant
Dim j As Variant
Dim i As Integer
Side note. You had a typo in Interger
Which is not what you really want, knowing that all of them are going to store numbers
Declare the objects that you're going to work with. For example, you refer to the sheet Sanctions three times in your code:
ActiveWorkbook.Sheets("Sanctions")
This can be set once like this:
Set targetSheet = ThisWorkbook.Worksheets("Sanctions")
And then reused in lines like this:
With Sheets("Sanctions")
or this:
Sheets("Sanctions").Range("NextRow")
by writing this:
With targetSheet
in this way, if you ever need to change it (the person working with your code, or your future you will be really thankful)
Declaring your variables to just letters, makes your code really hard to understand.
Dim j,k,l
is different when you have:
Dim lastRow As Long
Dim lastColumn As Long
etc.
I suggest that you use the key F8 and step through the code, and see the logic behind it. That way you can learn more.
Code:
Public Sub ConditionalRowCopy()
' Declare object variables
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet
Dim cell As Range
' Declare other variables
Dim sourceLastRow As Long
Dim targetLastRow As Long
' Set a reference to the sheets so you can access them later
Set sourceSheet = ThisWorkbook.Worksheets("PEP")
Set targetSheet = ThisWorkbook.Worksheets("Sanctions")
' Find last row in source sheet based on column "R"
sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "R").End(xlUp).Row
' Find cell with word "Emetteurs", search in column R)
For Each cell In sourceSheet.Range("R1:R" & sourceLastRow).Cells
' If match
If cell.Value = "Emetteurs" Then
' Find last row in target sheet based on column "A"
targetLastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
' Copy entire row to next empty row in target sheet
cell.EntireRow.Copy Destination:=targetSheet.Range("A" & targetLastRow).Offset(RowOffset:=1)
End If
Next cell
End Sub
Let me know if it works!

Using excel formula to copy a column between workbooks if first cell contains any info

I'm tyring to look for a way to return a range of cells with just the lookup function. Is this really possible?
Basically like this:
=LOOKUP([MasterBook.xlsm]Sheet3!$A:$A,?)
I just want the function to look in the main workbook through all of Column A and return all cells for Column A that have something in them.
EDIT for poster below:
Sure. I have two workbooks; one workbook is essentially a local product that has a "master" sheet on top and then individual worksheets following it that have all of their information extracted from the master sheet. The second workbook is a local copy of a product that I send to a non-local entity higher up the food chain. Basically I need to pull information from the individual sheets in my first workbook and put it in the appropriate columns in the second workbook. I have a macro that gets the info from my sheets in the one workbook over to the other, but the second workbook is formatted differently. I was looking for a way to use a formula if possible.
The macro I am referring to is:
Sub CopyTest()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Workbooks("Local Workbook.xlsm").Worksheets("Sheet3").Columns("A")
Set targetColumn = Workbooks("Nonlocal Workbook.xlsm").Worksheets("Sheet1").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
All this does is pull the specified column from one sheet and put it in the column on the second book; but it just pastes it starting in the first block. Since the non-local book is formatted differently, the column I need to transfer to doesn't start until Row 9. shrug I have ideas abuot what I'm trying to do with this, but my ideas tend to exceed my technical ability (which occasionally makes it difficult to explain). :)
Depending on how different your workbooks are formatted. Here is two way to handle this:
Adapt your macro
Instead of copying the whole column, you can copy paste, only the values you want to.
Here is an example:
Sub CopyTest()
Dim rSource As Range, rTarget As Range
Dim lEnd As Long
lEnd = Range("A65536").End(xlUp).Row
Set rSource = Workbooks("Local Workbook.xlsm").Worksheets("Sheet3").Range("A1:A" & lEnd)
Set rTarget = Workbooks("Nonlocal Workbook.xlsm").Worksheets("Sheet1").Range("A9")
rSource.Copy Destination:=rTarget
End Sub
Use a formula
If your data are not in the same order, you'd better use a VLOOKUP formula.
See how it works.
Don't hesitate to post another question with what you've built for some help. Please give as much details as possible so we could help you the best way.
[EDIT] Another try following the comments
Option Explicit
Dim wTarget As Workbook
Sub mainCopy()
Dim bGo As Boolean
bGo = True
'Add a new workbook to copy the data - do you want the user to select one?
Set wTarget = Application.Workbooks.Add()
Do While bGo
CopyTest
bGo = MsgBox("Do you want to import data from another workbook?", vbYesNo, "Continue?")
Loop
End Sub
Sub CopyTest()
Dim rSource As Range, rTarget As Range
Dim lEnd As Long, lCol As Long
Dim ws As Worksheet
Dim vFile As Variant
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
For Each ws In ActiveWorkbook.Worksheets
'do you need to copy the columns separately?
' For lCol = 1 To 10
'find the last cell of the 10th column
lEnd = ws.Cells(65536, 10).End(xlUp).Row
Set rSource = ws.Range("A1:J" & lEnd)
'How can we define the target worksheet?
Set rTarget = wTarget.Worksheets("Sheet1").Range("A9")
rSource.Copy Destination:=rTarget
' Next lCol
Next ws
End Sub

Resources