Excel VBA - Select All Columns & Rows After Last Occupied Column & Row - vba

I'm trying to figure out the code that identifies the last occupied column in the sheet then deletes all columns after that. I'm also trying to figure out the code that identifies the last occupied row in the sheet then delete all rows after that.
So far I've got the idea that I will need to use Rows.Count function but I'm having trouble getting it to select the entire rows after the last occupied row. Same for columns... This is what I've come up with so far which only identifies the last occupied row. Does anyone know how to get it to now select the entire rows after this? And similarly for the entire columns? I can't seem to figure out the code to select the last occupied column like I can with rows... Thank you in advance
Rows:
Sheets("ppCopy").Cells(Rows.Count, 1).End(xlUp).Row

You need to read the code and try to make sense of it and the answer will come to you.
Break down what you already know.
Sheets("ppCopy").Cells(Rows.Count, 1).End(xlUp).Row
Rows.Count = Last Available Row
End(xlUp) = move UP from the last available row (Rows.Count) to the last used row.
How do you get the column then?
Sheets("ppCopy").Cells(1, Columns.Count).End(xlToLeft).Column
Columns.Count = Last Available Column
End(xlToLeft) = Move Left from the last available column (Columns.Count) to the last used Column.
Here is how to delete unused Rows and Columns:
Sub deleteUnused()
Dim lastRow As Long, lastColumn As Integer 'there are a lot of rows compared to columns
Dim lastLetter As String, firstLetter As String
Set wk = ThisWorkbook
With wk.Sheets("Sheet1")
'Get last used rows and columns based on valued from Column A and Row 1
lastRow = .Cells(Excel.Rows.Count, 1).End(Excel.xlUp).Row
lastColumn = .Cells(1, Excel.Columns.Count).End(Excel.xlToLeft).Column
'Delete Rows
.Rows("" & (lastRow + 1) & ":" & Excel.Rows.Count & "").EntireRow.Delete Shift:=xlUp
'Delete columns, tricky because you need the Column Letters instead of the numbers
lastColumn = lastColumn + 1
firstLetter = Split(.Cells(, lastColumn).Address, "$")(1)
lastLetter = Split(.Cells(, Excel.Columns.Count).Address, "$")(1)
.Columns("" & firstLetter & ":" & lastLetter & "").EntireColumn.Delete Shift:=xlLeft
End With
End Sub

J Doe
Here is a code that will search for the value in any cell on any column and then select and delete all rows after that and do the same for the columns. No a very technic or something but will do the work and also give you some ideas. It will also include formulas that display empty cells.
Hope this help.
Sub DeleteRowAndColumns()
With ThisWorkbook.Sheets("ppCopy")
'find any cell no empty in a row in any row
.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Offset(1, 0).EntireRow.Select
'select all the rows
.Range(Selection, Selection.End(xlDown)).Select
Selection.Delete ' clear all the rows
'find the last value in any column
.Cells.Find(What:="*", SearchOrder:=xlColumns, SearchDirection:=xlPrevious, LookIn:=xlValues).Offset(0, 1).EntireColumn.Select
'select columns
.Range(Selection, Selection.End(xlToRight)).Select
Selection.Delete 'clear columns
End With
End Sub

Related

copying the rows one below another checking on the last filled column

I have a sheet List. I want the contents of list to be transferred to my sheet Evaluation. But my evaluation sheet, already consist of the previous evaluation. I want the new rows just below the old ones. Can some one help how I can achieve this ?
I have the below code with me, which is a copy paste functionality.
Sub lastweekctt()
Worksheets("List").Range("A4:W1000").Copy _
Destination:=Worksheets("Evaluation").Range("A5")
End Sub
I have my header in row 4 in both the sheets.
You need to get last blank row:
Sub lastweekctt()
Dim LastRow As Long
'get last row
LastRow = Worksheets("Evaluation").Cells(Rows.Count,1).End(xlUp).Row
Worksheets("List").Range("A4:W1000").Copy _
Destination:=Worksheets("Evaluation").Range("A" & LastRow + 1)
End Sub
Hope this help.
You will need to find the last row first
lLastRow = Worksheets("Evaluation").Cells(Worksheets("Evaluation").Rows.Count, 1).End(xlUp).Row
and then your destination range will look like this
.Range("A" & lLastRow + 1)

How to get VLOOKUP to select down to the lowest row in VBA?

Looking to automate the insertion of a VLOOKUP formula in a cell.
When recording the macro I instruct it to populate the columns below with the same formula. Works great, however, there is an issue when the table that the VLOOKUP searches through changes (more or less rows).
As it's recorded, the VLOOKUP drops down to the final row in the table (273). However, I want to set it up so that it will go down to the very last row. Meaning that I can run the script on tables of varying numbers of rows.
Selected columns will remain the same.
Range("AJ2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-20], Previous!R2C2:R273C22,17,FALSE)"
try this:
With Worksheets("Previous")
Range("AJ2").FormulaR1C1 = _
"=VLOOKUP(RC[-20], Previous!R2C2:R" & .Cells(.Rows.Count, 2).End(xlUp).Row & "C22,17,FALSE)"
End With
where:
Range("AJ2")
will implicitly reference the ActiveSheet
.Cells(.Rows.Count, 2).End(xlUp).Row
will reference "Previous" worksheet, being inside a With Worksheets("Previous")- End With block
#nbayly said it, plenty of posts on this. Infact i have provided an answer to this before here:
How to Replace RC Formula Value with Variable
below is slightly modified for a dynamic range, which is what i believe you are looking for
For j = n To 10 Step -1
If Cells(j, 1).Value = "" Then
Cells(j, 1).Formula = "=VLookup(RC20,Previous!R2C2:R273C22,17,FALSE)"
End If
Next j
remember to define j as long and n=sheets("sheetname)".cells(rows.count,1).end(xlup).row
replace 10 in j = n to 10 with the starting row number

Copying several filtered columns' worth of non blank cells to second sheet

I have a table that I need to autofilter itself according to criteria in column "AS", then copy multiple discrete columns' worth of resulting non-blank cells to specific cells in the next sheet.
What is the most efficient way of doing this? I'm aware that I may have to copy/paste specialvalues instead of direct reference
I'm not entirely sure what you're asking. But, imagine Column A is filled with names of fruits and Column B is filled with numbers. The following code filters Column A with the criteria "Apples" and copies the corresponding numbers to a new worksheet. This might start you off on the right track.
Sub selectApples()
' Find last row in column A
Dim LastRow As Integer
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
' Select data in column A and filter
Range("A1:A" & LastRow).Select
Selection.AutoFilter Field:=1, Criteria1:="Apples"
'Find new last row
Dim newLastRow As Integer
newLastRow = Cells(Rows.Count, 1).End(xlUp).Row
'Copy and paste special into new worksheet
Range("B2:B" & newLastRow).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
Selection.PasteSpecial Paste:=xlPasteValues
End Sub

I need a VBA code to count the number rows, which varies from ss to ss, return that number and copy and paste that row and all other columns

I have vba question I have been trying to find the answer for for a long time. I have numerous spreadsheets from numerous clients that I run macro's on, I'm new to coding and have been able to mostly figure out what I need to do. My clients send us data monthly and every month the number of rows change. The columns don't change but the amount of data does. My previous macro's I have just chosen the entire column to copy and paste onto our companies template. This worked fine for must things but has created some really long code and macros take a long time. I would like to write a code that counts how many rows are in a certain column and then from there copies and pastes that however many rows it counted in each column. Only a few columns contain data in every row, so I need it to count the rows in one specific column and apply to that every column. Any help would be appreciated.
Thanks
Tony
Hi Guys,
Still having issues with this, below I pasted the code I'm using if anyone can see why it won't run please help.
Windows("mmuworking2.xlsx").Activate
Workbooks.Open Filename:= _
"C:\Users\I53014\Desktop\QC DOCS\Sample_Data_Import_Template.xlsx"
Windows("mmuworking2.xlsx").Activate
Dim COL As Integer
COL = Range("A:DB").Columns.Select
**Range(Cells(2, COL), Cells(Range("E" & Rows.Count).End(xlUp).Row, COL)).Copy Destination:=Windows("Sample_Data_Import_Template.xlsx").Range("A2")**
Range("A2").Paste
Range("A5000").Formula = "='C:\Users\I53014\Desktop\[Import_Creator.xlsm]sheet1'!$B$2"
ActiveWorkbook.SaveAs Filename:="Range (A5000)", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
I bolded where it keeps stopping.
This should give you the last row containing data:
ActiveSheet.UsedRange.Rows.Count
This will give you the last row in a specific column:
Range("B" & Rows.Count).End(xlUp).Row
here is an example of how I can copy every row in the first three columns of a worksheet
Sub Example()
Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, 3)).Copy Destination:=Sheet2.Range("A1")
End Sub
You have to be careful as there are some caveats to both methods.
ActiveSheet.UsedRange may include cells that do not have any data if the cells were not cleaned up properly.
Range("A" & Rows.Count).End(xlUp).Row will only return the number of rows in the specified column.
Rows(Rows.Count).End(xlUp).Row will only return the number of rows in the first column.
Edit Added an example
Edit2 Changed the example to be a bit more clear
For this example lets say we have this data
You could copy any other column down to the number of rows in column A using this method:
Sub Example()
Dim Col as Integer
Col = Columns("C:C").Column
'This would copy all data from C1 to C5
'Cells(1, Col) = Cell C1, because C1 is row 1 column 3
Range(Cells(1, Col), Cells(Range("A" & Rows.Count).End(xlUp).Row, Col)).Copy Destination:=Sheet2.Range("A1")
End Sub
The end result would be this:

Delete duplicate entries in a column in excel 2003 vba

Well the question is, I have got a column, for example column Y has many entries in it, nearly 40,000 and It increases everyweek. The thing is I have to check for duplicates in Y column and delete the entire row. Thus, Y column should have only unique entries.
Suppose I have 3,000 entries and after 1 week, i'll have about 3,500 entries. Now I have to check these newly added 500 columnn values not the 3,500 with the old + the new i.e 3,500 entries and delete the duplicated row. The old 3,000 shouldn't be deleted or changed. I have found macros but they do the trick for the entire column. I would like to filter the new 500 values.
Cells(2, "Q").Formula = "=COUNTIF(P$1:P1,P2)=0" 'I have used these formula
Range("Q2").Copy Destination:=Range("Q3:Q40109") 'it gives false for the duplicate values
I know we have to use countif for the duplicate entries. But what Iam doing is applying the formula and then search for false entries and then delete it. I belive applying formula and finding false and then deleting its little bit time consuming.
Sub DeleteDups()
Dim x As Long
Dim LastRow As Long
LastRow = Range("A65536").End(xlUp).Row
For x = LastRow To 1 Step -1
If Application.WorksheetFunction.CountIf(Range("A1:A" & x), Range("A" & x).Text) > 1 Then
Range("A" & x).EntireRow.Delete
End If
Next x
End Sub
This is what I found on google but i dont know where the error is. It is deleting all the columns if i set
For x = LastRow To 1 Step -1
For x = LastRow to step 3000 ' It is deleting all 500 columns but if it is -1 working fine
Any modifications need to be done for these function? or sugest me any good function that helps me. Check for the duplicate values of a selected column range from the entire column. I mean check 500 entires column values with the 3500 column entry values and delete the duplicates in 500 entries
Thanks in advance
This should be rather simple. You need to create 1 cell somewhere in your file that you will write the cell count for column Y each week after removing all dupes.
For example, say week1 you remove dupes and you are left with a range of Y1:Y100. Your function will put "100" somewhere in your file to reference.
Next week, your function will start looking from dupes from (cell with ref number) + 1, so Y:101 to end of column. After removing dupes, the function changes the ref cell to the new count.
Here is the code:
Sub RemoveNewDupes()
'Initialize for first time running this
If Len(Range("A1").Value) = 0 Then
Range("A1").Value = Range("Y" & Rows.count).End(xlUp).row
End If
If Range("A1").Value = 1 Then Range("A1").Value = 0
'Goodbye dupes!
ActiveSheet.Range("Y" & Range("A1").Value + 1 & ":Y" & _
Range("Y" & Rows.count).End(xlUp).row).RemoveDuplicates Columns:=1, Header:=xlNo
'Re-initialize the count for next time
Range("A1").Value = Range("Y" & Rows.count).End(xlUp).row
End Sub
*sorry no idea why auto-syntax highlighting makes this hard to read
Update:
Here is a way to do it in Excel 2003. The trick is to loop backwards through the column so that the loop isn't destroyed when you delete a row. I use a dictionary (which I'm famous for over-using) since it allows you to check easily for dupes.
Sub RemoveNewDupes()
Dim lastRow As Long
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Len(Range("A1").Value) = 0 Then
Range("A1").Value = 1
End If
lastRow = Range("Y" & Rows.count).End(xlUp).row
On Error Resume Next
For i = lastRow To Range("A1").Value Step -1
If dict.exists(Range("Y" & i).Value) = True Then
Range("Y" & i).EntireRow.Delete
End If
dict.Add Range("Y" & i).Value, 1
Next
Range("A1").Value = Range("Y" & Rows.count).End(xlUp).row
End Sub
How can Excel know that entries are "new"? (e.g. how can we know we only have to consider the 500 last rows)
Actually, if you already executed the macro last week, the first 3,000 rows won't have any duplicates so the current execution won't change these rows.
The code your described should nearly work. If we keep it and change it very slightly:
Sub DeleteDups()
Dim x As Long
Dim LastRow As Long
LastRow = Range("Q65536").End(xlUp).Row
For x = LastRow To 1 Step -1
'parse every cell from the bottom to the top (to still count duplicates)
' and check if duplicates thanks to the formula
If Range("Q" & x).Value Then Range("Q" & x).EntireRow.Delete
Next x
End Sub
[EDIT] Another (probably faster) solution: filter first the values and then delete the visible rows:
Sub DeleteDups()
ActiveSheet.UsedRange.AutoFilter Field:=17, Criteria1:="True" 'filter column Q for True values
ActiveSheet.Cells.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End Sub
Couldn't test this last solution right here, sorry.
Here's an idea:
Sub test
LastRow = Range("A65536").End(xlUp).Row
For i = LastRow To 1 Step -1
If Not Range("a1:a" & whateverLastRowYouWantToUse ).Find(Range("a" & i).Value, , , , , xlPrevious) Is Nothing Then
Rows(i).Delete
End If
Next i
End Sub
It checks the entire range above the current cell for a single duplicate. If found, it the current row is deleted.
EDIT I just realized in your example, you said column Y, but in your code you are checking A. Not sure if the example was just a hypothetical, but wanted to make sure that wasn't the reason for the odd behavior.
Note, this is untested! Please save your workbook before trying this!