Delete rows from list - excel

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

Related

VBA - Copy, Paste then move to next row until reaching blanks

Essentially, I have data in three columns and a model on a separate tab. The data tab has 1,000 rows of data, and each entry will be run through the model, with results being pasted into the fourth column.
Here's what one iteration would look like, but I need it to loop through every row.
Worksheets("Data").Range("E2:G2").Copy _
Worksheets("Model").Range("B4:D4").PasteSpecial Paste:=xlPasteValues
Calculate
Worksheets("Model").Range("C120").Copy_
Worksheets("Data").Range("H2").PasteSpecial Paste:=xlPasteValues
Worksheets("Model").Range("C121").Copy_
Worksheets("Data").Range("I2").PasteSpecial Paste:=xlPasteValues
Worksheets("Model").Range("C122").Copy_
Worksheets("Data").Range("J2").PasteSpecial Paste:=xlPasteValues
Then we'd copy the next row of data from the Data tab (i.e., range E3:G3).
This seems like a classic loop scenario, but I don't know how to write it in VBA.
You can do this on a range, I see two ways you can do it, using a copy and paste or simply replicating a transposed version of the data:
'Copy and paste method
Worksheets("Model").Range("C120:C" & range("C" & rows.count).end(xlup).row).Copy 'Using the .end(xlup) will find the last row of data without looping until blank.
Worksheets("Data").Range("H2").PasteSpecial xlPasteValues,,,True 'The True here is what tells the pastespecial to transpose
'Transpose method
Worksheets("Data").Range("H2:J2").Value = application.transpose(Worksheets("Model").range("C120:C122"))
Each have their advantage, the Copy and Paste method is easier because you don't need to know the end column so it works easier for a dynamic range, the transpose method doesn't use the clipboard so is less impact on your system.
The better method code wise would be the transpose method.
You can then set up a simple For Next loop to run through as many data ranges as you want.
Dim DataRow As Long, MyDat As Worksheet, MyModel As Worksheet
Set MyDat = Worksheets("Data")
Set MyModel = Worksheet("Model")
For DataRow = 2 To MyDat.Range("E" & Rows.Count).End(xlUp).Row
MyModel.Range("B4:D4").Value = MyDat.Range("E" & DataRow & ":G" & DataRow).value
Calculate
MyDat.Range("H" & DataRow & ":J" & DataRow).Value = Application.Transpose(MyModel.Range("C120:C122"))
Next
This is a simple loop that finds the last row in "Data" and uses it for the loop defined in "Model".
The expected result of this is that the loop will begin at row 120 and continue until the last row in "Data", copying data from C120 through to C(lRow) and pasting it into the "Data" sheet.
Sub test()
' declare your variables so vba knows what it is working with
Dim lRow, i As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim srcws As Worksheet: Set srcws = wb.Worksheets("Data")
Dim destws As Worksheet: Set destws = wb.Worksheets("Model")
' find the last row in Data
lRow = srcws.Cells(srcws.Rows.Count, 1).End(xlUp).Row
' iterate from 120 to the last row found above
For i = 120 To lRow
' copy /paste the data
srcws.cells(1, 3).Copy Destination:=destws.cells(2, 7 + i)
Next i
End Sub
Best way is to use the cells-function, where the first argument is the row and the second is the column. Since you want to inrement the source to copy from by one row at a time but increment the paste destination by one column by a time, this method will be suitable.
In addition, try to not use "copy-paste", focus on setting the value for a cell by referring to a the value attribute from the source to copy. Each time you copy and then paste into the destination, you will need an additional memory cell, resulting in a much longer elapsed time if you are working with a large range to copy.
The code below should do the job.
Sub CopyData()
Dim i As Integer
i = 8 ' Start pasting into column H
' Loop until a blank cell is found
Do While Not Selection.Value = 0
With Sheets("Data").Cells(i + 112, 3)
' Select each cell in "Data", starting on C120
.Select
' Copy the value into "Model", starting on H2
Sheets("Model").Cells(2, i).Value = .Value
End With
Loop
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.

Working with the Columns function - Excel VBA

I have been looking around the site for a while for an answer to this question but no luck just yet. I have this code where I loop through a row of numbers and depending on what number is in the cell at the time, determines what I copy and paste to the sheet. I am using Columns for this because it is the only way I can make my code dynamic. It works but when I paste I would like to paste in cells lower than where it's pasting right now. I was wondering if Columns had a way of specifying what column and where to paste my data.
Code:
Dim sh As Worksheet
Dim rw As Range
Dim row As Range
Dim cell As Range
Dim RowCount As Integer
Set rw = Range("A5:CG5")
Set sh = ActiveSheet
For Each row In rw.Rows
For Each cell In row.Cells
Select Case cell.Value
Case "2"
ThisWorkbook.Worksheets("Sheet1").Range("E27:E51").Copy Destination:=Sheets("Sheet2").Columns(4)
End Select
Next cell
Next row
Your problem can be solved as Jeeped said, use Destination:=Sheets("Sheet2").Cells(27, 5) or Destination:=Worksheets(2).Range("E27")
Since you want to learn a little bit more, i made an example explanation:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-column-property-excel
On the link it is explained that .Column:
Column A returns 1, column B returns 2, and so on.
And the same is with the .Rows
Use .Cells https://msdn.microsoft.com/pt-br/library/office/ff194567.aspx So you can use the .Cells(Rows,Columns) or .Cells(Index from a Range) or the entire Object:
With Worksheets("Sheet1").Cells.Font
.Name = "Arial"
.Size = 8
End With
So an example if you want to turn your spreadsheet dynamical: to copy from range $E$27 to last row with something written from column $E on Sheet1 To
the last column with nothing written on row 1 on Sheet2.
Sub test()
'Declare variables here
Dim sht1, sht2 As Worksheet
'sht1 has the data and sht2 is the output Worksheet, you can change the names
last_row = Worksheets(1).Range("E65536").End(xlUp).Row
last_column = Worksheets(2).Cells(1, sht1.Columns.Count).End(xlToLeft).Column
'Data add
For i = 27 To last_row
'Start from Row 27
Worksheets(2).Cells(i - 26, last_column + 1) = Worksheets(1).Cells(i, 5)
Next i
MsgBox "Data Updated"
End Sub
And an example of a basic dynamical workbook with i=i+1 and For loops split a single row of data into multiple unique rows into a new sheet to include headers as values and cell contents as values

select all rows for column except header in a seperate worksheet

I've tried various ways and answers to select all of the rows except the header for a certain column and none seem to work.
I've tried using (15 is the column here):
Range(Cells(2, 15), Cells(.Cells(rows.Count, 15).End(xlUp).Row, 15)).Select
I managed to use .Activate on the worksheet with a different statement to select all, but this changes the sheet and you could visibly see all the rows being selected. This isn't possible for what I need it for. Users can't have a bunch of sheets constantly being switched in front of them, makes for a bad experience.
How can I select all of the non-blank columns after the header (first) row without using .Activate?
I need to get these values, put them in an array, and check if the current cell value is in the array. Not asking for this part, but providing it as context if it matters.
You can not select a range on a non-active worksheet.
Here is how you can set a reference to all the cells in a column except the header row.
Dim TargetRange As Range
With Worksheets("Sheet1")
Set TargetRange = .Range(.Cells(2, 15), .Cells(Rows.Count, 15).End(xlUp))
End With
The following code reads the data from the Worksheet (without using Select or Activate), and puts it in a 2-dimensional array.
Option Explicit
Sub Range_WO_Headers()
Dim Sht_Source As Worksheet
Dim Rng As Range
Dim LastRow As Long
Dim LastCol As Long
Dim Rng_Array As Variant
' modify Sheet1 according to your sheet name
Set Sht_Source = ActiveWorkbook.Worksheets("Sheet1")
' assuming the table's data starts from Cell A1
LastRow = Sht_Source.Cells(Sht_Source.Rows.Count, "A").End(xlUp).Row
LastCol = Sht_Source.Cells(1, Sht_Source.Columns.Count).End(xlToLeft).Column
' resize array according to number of columns and number of rows
ReDim Rng_Array(0 To LastRow, 0 To LastCol)
' set dynamic array from Cell A1 to last row and last column found (starting the second row)
Set Rng = Sht_Source.Range(Cells(2, 1), Cells(LastRow, LastCol))
Rng_Array = Application.Transpose(Rng)
End Sub

Re: Take a value (that is summed) in multiple sheets and insert into a master sheet

Re: Creating a master sheet from multiple sheets.
Multiple sheet description: table with many rows and columns. Columns headings are identical but rows vary. Each sheet is a date.
Task: to take a single value from a specific column (always happens to be column M). the value I want is the total of that column. Take this summed value and insert into a master sheet.
My attempt so far is:
Sub append_master_sheet()
Dim wAppend As Worksheet, wSheet As Worksheet
Dim LastRow As Long
Set wAppend = Worksheets("Master")
For Each wSheet In Worksheets
If wSheet.Name <> wAppend.Name Then
LastRow = WorksheetFunction.Max(3, wAppend.Cells(65536, 2).End(xlUp).Row)
wSheet.UsedRange.Resize(, 13).Copy Destination:=wAppend.Cells(LastRow, 2)
End If
Next wSheet
End Sub
1). it takes all 13 columns rather than only the 13th column. (I see that is because I have set it at 13 as I do not know how to cycle through the preceding columns and skip them to only return the 13th column data (and within this column return the total of the column, not the discrete line items
2) Besides returning all the data which is a problem, it actually consistently skips the final value in the column M.
Can you advise how to amend above code to
1) only return the summed value from column M in the multiple sheets (calendar dates) and insert into master.
thanks,
N
Is this what you are trying (UNTESTED)
Like I mentioned in the comment above, see THIS link on how to find a last row in a column.
I have commented the code so that you will not have a problem understanding it. But if you do, simply post back :)
Note: I am assuming that the last cell in Col M has the SUM
Option Explicit
Sub append_master_sheet()
Dim wAppend As Worksheet, wSheet As Worksheet
Dim wApLRow As Long, wShLRow As Long
Set wAppend = ThisWorkbook.Worksheets("Master")
'~~> Get the last row where the ouput should be placed
wApLRow = wAppend.Range("B" & wAppend.Rows.Count).End(xlUp).Row + 1
For Each wSheet In Worksheets
If wSheet.Name <> wAppend.Name Then
With wSheet
'~~> Fuind the last row in Col M which has the sum
wShLRow = .Range("M" & .Rows.Count).End(xlUp).Row
'~~> Copy over the values to Master Sheet
wAppend.Range("B" & wApLRow).Value = .Range("M" & wShLRow).Value
'~~> Increment the row for next output
wApLRow = wApLRow + 1
End With
End If
Next wSheet
End Sub

Resources