How would you delete rows in excel such that Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select will not select the now empty rows - excel

The issue is that I have a function that deletes rows containing specific text:
Sub DeleteRowsContaining(text As String)
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
With ActiveSheet
'Set the first and last row to loop through
Firstrow = .UsedRange.Cells(2).Row
Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
'We loop from Lastrow to Firstrow (bottom to top)
For Lrow = Lastrow To Firstrow Step -1
'We check the values in the A column
With .Cells(Lrow, "A")
If Not IsError(.Value) Then
If .Value = text Then .EntireRow.Delete
'This will delete each row with the Value of text
'in Column A, case sensitive.
End If
End With
Next Lrow
End With
End Sub
After executing this code block I then would like to select the remaining text, however, any rows that were deleted from the end of a column still count when using the
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
command. The real issue is the error that happens when using the next command which is
Selection.End(xlDown).Offset(1, 0).Select
When using that command, if you have more than two empty rows selected, an error will be thrown. At this point I am at a loss, as all the ways that I can easily and dynamically check for the end of my data range are returning the location of a blank cell.
I am not sure if there is another way to delete a row that does not leave a cell selectable as if it had data, or if there is a way to trim the empty rows from a selection when excel seems to believe that the rows have something there.

Once you have completed deleting unwanted rows, to select the rows that remain run:
Sub SelectTheRest()
Dim N As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
Range("A1:A" & N).EntireRow.Select
End Sub

Related

Update an Empty Cell in a range

I'm looking to update a cell on a sheet when it's left empty. If there is data in column B but not in column AA, I need to insert something into column AA.
I have made the following code but have failed to make it update the cell:
Range("B2").Select
Do Until IsEmpty(ActiveCell)
Dim LoopRowNo As Integer
LoopRowNo = ActiveCell.Row
If IsEmpty(Range(Cells(LoopRowNo, 26))) Then Range(Cells(LoopRowNo, 26)).Value = "01/01/1990"
ActiveCell.Offset(1, 0).Select
Loop
Hoping someone can point me in the right direction.
Use Range or Cells, but not both.
Don't Select.
With ActiveSheet
Dim lastRow As Long
lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
Dim i As Long
For i = 2 to lastRow
If IsEmpty(.Cells(i, "AA")) And Not IsEmpty(.Cells(i, "B")) Then
.Cells(i, "AA").Value = "01/01/1990"
End If
Next
End With

How to insert row at the end of a range in Excel with VBA

I'm trying to insert a row at the bottom of the range, but nothing happens when I run the below code. If I remove the "1" in
Cells(nextRow, 1).EntireRow.Insert
It will insert a row at the top of the range.
Sub newRow()
Application.ScreenUpdating = False
Sheet1.Activate
'goes to the row at the bottom of the range
nextRow = Cells(Rows.Count, 1).End(xlUp).row + 1
'inserts new row
Cells(nextRow, 1).EntireRow.Insert
Application.ScreenUpdating = True
End Sub
Inserting a row at the bottom of the range is not visible - and it is an empty row, which is not different than the unused empty rows. Anyway, inserting a row before the last one of the range is quite visible:
Sub NewRow()
Dim nextRow As Long
With Sheet1
nextRow = .Cells(.Rows.Count, 1).End(xlUp).Row
.Cells(nextRow, 1).EntireRow.Insert
End With
End Sub
Usin With Sheet1 and .Cells() instead of Select and Activate is a good practice -How to avoid using Select in Excel VBA

Excel VBA: Delete rows if value not equal to a value?

So I've been searching hard to find why my code hasn't been working, but every time I try, I get a result where nothing is changed. Can someone please tell me what I'm missing? Sorry, I'm a total novice but I'm trying.
Dim Cell As Range
With Sheets(1)
' loop column D until last cell with value (not entire column)
For Each Cell In .Range("D2:D" & .Cells(.Rows.Count, "D").End(xlUp).Row)
If Cell.Value <> 110 Then
Rows(Cell.Row).EntireRow.Delete
End If
Next Cell
End With
Instead of looping, make use of excels inbuilt functions, its cleaner and more concise.
With Sheets(1).UsedRange
.AutoFilter Field:=4, Criteria1:="<>110"
.Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
.AutoFilter
End With
if you insist on looping then use the following code:
With Sheets(1).UsedRange
For lrow = .Rows.Count To 2 Step -1
If .Cells(lrow, 4).Value <> 110 Then .Rows(lrow).Delete
Next lrow
End With
Untested, but maybe something like:
Option explicit
Sub DeleteRows()
With thisworkbook.worksheets(1)
' loop column D until last cell with value (not entire column)
Dim lastRow as long
lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
Dim rowIndex as long
For rowIndex = lastRow to 2 step -1
If .cells(rowIndex, "D").value2 <> 110 then
.cells(rowIndex, "D").entirerow.delete
End if
Next rowIndex
End With
End sub
If you have a lot of rows, you could use union to build a range consisting of all rows to be deleted, then delete them in one go.

Make last cell in row active

How can I, using the code below, replace "B5" by the "LastCol" so that I can activate the last non-blank cell in a row?
Sub LastColumnInOneRow()
'Find the last used column in a Row: row 1 in this example
Dim LastCol As Integer
With ActiveSheet
LastCol = .Cells(6, .Columns.Count).End(xlToLeft).Column
End With
Worksheets("WARNINGS").Range("B5").Activate
ActiveCell.Offset(2, 0).Activate
End Sub
Thank you
You could do like this:
Sub LastColumnInOneRow()
'Find the last used column in a Row: row 1 in this example
Dim LastCol As Integer
With ActiveSheet
LastCol = .Cells(6, .Columns.Count).End(xlToLeft).Column
End With
With Worksheets("WARNINGS")
.Activate
.Cells(5,LastCol).Activate
End With
ActiveCell.Offset(2, 0).Activate
End Sub
The question took me a minute to figure out but try this
Worksheets("WARNINGS").Cells(6, LastCol + 1).Activate
at the end.
Sub LastColumnInOneRow()
'Find the last used column in a Row: row 1 in this example
Dim LastCol As Long
With ActiveSheet
LastCol = .Cells(6, .Columns.Count).End(xlToLeft).Column
End With
Worksheets("WARNINGS").Cells(6, LastCol + 1).Activate
End Sub
Excellent! Many thanks. Here is the one I used at the end.
This was a first step towards sorting a pivot table results.
I saved a macro to sort the values but am now getting a "Subscript out of Range" warning when I try to run it. I guess the macro script is using a static range that I need to replace so that it can run to whatever Pivot Table results I may have.
But which line of the macro code do I need to replace?
Sub SortLargestWarningsCount()
'Find the last used column in a Row: row 1 in this example
Dim LastCol As Integer
With ActiveSheet
LastCol = .Cells(6, .Columns.Count).End(xlToLeft).Column
End With
Worksheets("WARNINGS").Cells(6, LastCol).Activate
ActiveCell.Offset(1, 0).Activate
'Sort from Largest
ActiveSheet.PivotTables("WarningsPivotTable").PivotFields( _
"[Warnings].[Column5].[Column5]").AutoSort xlDescending, _
"[Measures].[Count of Column5]", ActiveSheet.PivotTables("WarningsPivotTable"). _
PivotColumnAxis.PivotLines(12), 1
End Sub

Excel Macro to add COUNTA to new top row

I have an Excel 2013 worksheet where each column has a header row, and then the word "DIRECT" in some or all of the cells. No other data exists in the columns, just "DIRECT" or blanks. No columns are blank, they all have "DIRECT" at least once.
I'm looking for a macro that does the following:
Adds a new top row
Ignores the original header row, but gets a count of the cells with "DIRECT" in them
Puts that number in the corresponding new top cell for each column
Does the above actions for each column in the worksheet
Works regardless of the last column or row with data (I have to run this on several different-sized worksheets)
I recorded a macro that gets close, but it has two problems:
It adds the COUNTA data out to the last row of the workbook, which isn't needed (the populated columns will be a couple hundred, not thousands)
It references a specific cell range, so could cut off data for sheets with more rows
Sub AddColumnCountsRecorded()
'
' AddColumnCounts Macro
'
'
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("J1").Select
ActiveCell.FormulaR1C1 = "=COUNTA(R[2]C:R[15]C)"
Range("J1").Select
Selection.Copy
Range(Selection, Selection.End(xlToRight)).Select
ActiveSheet.Paste
End Sub
If it helps:
Column "A" can determine the last row where data could be (that's the "username" column", so no blanks there) - although this last row will also change from sheet to sheet.
Row 2 (the header row) can determine the last column where data could be - it has no blank columns; in each column, at least one cell will have the word "DIRECT".
Any advice on editing the existing macro or concocting a new one from scratch would be greatly appreciated!
Thanks!
UPDATE:
Much thanks to Scott, here's what I ended up with - this adds the non-blank cell count to the active worksheet and stops at the last row with data in it. I just call it directly, without the 2nd section of code proposed below:
Sub AddColumnCountsRecorded()
With ActiveSheet
.Rows("1:1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Dim lRow As Long, lCol As Long
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
.Range(.Cells(1, 2), .Cells(1, lCol)).FormulaR1C1 = "=COUNTA(R[2]C:R[" & lRow & "]C)"
End With
End Sub
Give this a shot. I made a separate sub that you can pass the worksheet reference too.
Sub AddColumnCountsRecorded(ws As Worksheet)
With ws
.Rows("1:1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Dim lRow As Long, lCol As Long
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
.Range(.Cells(1, 2), .Cells(1, lCol)).FormulaR1C1 = "=COUNTA(R[2]C:R[" & lRow & "]C)"
End With
End Sub
Call it like this:
Sub ColumnCount()
AddColumnCountsRecorded Worksheets("Sheet1")
End Sub

Resources