How to delete all blank rows - vba

This code makes Excel non-responsive. Anyone know why that might be?
Sub delblank()
On Error Resume Next
ActiveSheet.UsedRange.Range("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
If Err Then
MsgBox "No blank cells"
End If
End Sub

The problem is that UsedRange won't accept Range("A:A") as a property because the used range in your sheet does not contain an entire column from top to bottom of the Excel sheet, i.e. from row 1 to row 1048756.
What you want instead is to refer to the first column of UsedRange: replace Range("A:A") by Columns(1) like this:
ActiveSheet.UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Now it works.
When you have a long chain of methods and properties giving you trouble like that, it's easier to break it down into its constituents in order to find the source of the error. That's what I did:
Dim r1 As Range
Dim r2 As Range
Dim r3 As Range
Dim sh As Worksheet
Set sh = ActiveSheet
Set r1 = sh.UsedRange
Set r2 = r1.Range("A:A") ' Aha, error occurs here! Wow, that was easy to find.
Set r3 = r1.SpecialCells(xlCellTypeBlanks)
r3.EntireRow.Delete
When the error is gone, it's fine to put the chain back together again to get rid of the clutter.
Also don't use On Error Resume Next unless you're absolutely certain that this is what you want, because it will just swallow errors and not tell you where they came from.

Try something like this:
Public Sub Tester()
On Error Resume Next
Columns(1).SpecialCells(xlBlanks).EntireRow.Delete
On Error GoTo 0
End Sub

Try below code
Sub delblank()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim rng As Range
On Error Resume Next
Set rng = ActiveSheet.UsedRange.Range("A:A").SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "No cells found"
Else
rng.EntireRow.Delete
End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

Related

No Cells Found on IF condition [duplicate]

I do some filtering on a range and copy that filtered range with
myRange.SpecialCells(xlCellTypeVisible).Copy
As soon as the filter filters all cases I get
Error 1004 No cells were found
I am looking for a way to check (without an On Error) if the filtered range is empty.
I already tried to set a range with lastRow = .Cells(.Rows.Count, ColumnName).End(xlUp).Row and check if lastRow > 0 but with this way I also count the filtered (or hidden) row contents.
I also tried
Sub test()
Dim rngStart As Range
Dim rngFiltered As Range
Set rngStart = Sheets(1).Range("A1:A6")
Set rngFiltered = rngStart.SpecialCells(xlCellTypeVisible).Select
If rngFiltered.Rows.Count = 0 Then
MsgBox ("No Cases")
Else
MsgBox ("Found Cases")
End If
End Sub
But here I get the error "No cells found" in the Set rngFiltered line as well.
I have no header row, since the filter is so complex that I programmed it without using the .Sort function
Dim rngStart As Range
Dim rngFiltered As Range
'...
'...
Set rngFiltered = Nothing '<<< reset rngFiltered if running this code in a loop...
On Error Resume Next
Set rngFiltered = rngStart.SpecialCells(xlCellTypeVisible)
On Error Goto 0
If not rngFiltered is Nothing then
rngFiltered.Copy
End If
'...
'...
I stored the solution into a function. Here I use an error on mechamism.
Function errorCatchEmptyFilter(ByRef rngstart As Range) As Boolean
errorCatchEmptyFilter = False
'here I get an error if there are no cells
On Error GoTo hell
Set rngFiltered = rngstart.SpecialCells(xlCellTypeVisible)
Exit function
hell:
errorCatchEmptyFilter = True
End Function
What I do is I am counting filtered rows :
Sheets("Sheet1").Range("A2:Z2").AutoFilter
Sheets("Sheet1").Range("A2:Z2").AutoFilter Field:=1, Criteria1:=filter1
If Sheets("Sheet1").AutoFilter.Range.Columns(4).SpecialCells(xlCellTypeVisible).Count > 1 Then
you can change number of column to suits your needs
Got the same problem, but for filtering named table, solved it this way*:
instead of applying several filters, I've added a column at the end of the table, with a formula that would return true for the rows I wanted to have filtered in, false for filtered out.
Then, I've applied one filter for that true value and added a cell that would count all true values in that column
in vba, firstly reapply filter for the table then if that counter is greater than 0 do .SpecialCells(xlCellTypeVisible).Copy, else skip to next step (i was doing that in a loop)
*I know that this question is from 2015, but I've ended here in 2019 googling similar problem so I'm leaving my solution.

Run time error 13 on For loop

I am trying to use a combobox in my user interface, but if none of the options are good for the user they can type it in but after if they have entered something I want to save it so next time it appears in the list. I have tried the following approach:
For i = Range("O3") To Range("O3").End(xlDown)
If Not i.Value = ComboType.Value Then
Range("O3").End(xlDown) = ComboType.Value
End If
Next i
But this gives the above error on the first line. I am not very familiar with For loops in VBA so I am hoping somebody can help me.
This is how to make the for-each loop from O3 to the last cell with value after O3:
Public Sub TestMe()
Dim myCell As Range
Dim ws As Worksheet
Set ws = Worsheets(1)
With ws
For Each myCell In .Range("O3", .Range("O3").End(xlDown))
Debug.Print myCell.Address
Next myCell
End with
End Sub
It is a good practise to declare the worksheet as well, because otherwise you will always work with the ActiveSheet of the ActiveWorkbook.

Type Missmatch when copy/pasting to visible cells only

I'm trying to copy and paste a list into visible cells only. For some reason I'm getting a type miss-match error and I don't understand why. When debugging the error occurs on the third line.
Sub Copy_Filtered_Cells()
Set from = Sheets(Sheet2).Range("I16831:I20610")
Set too = Application.InputBox("J4:J16821", Type:=8)
For Each Cell In from
Cell.Copy
For Each thing In too
If thing.EntireRow.RowHeight > 0 Then
thing.PasteSpecial
Set too = thing.Offset(1).Resize(too.Rows.Count)
Exit For
End If
Next
Next
End Sub
Best to use Option Explicit at top of module, I am guessing at what you are trying to achieve. Here is a stab...
Option Explicit
Sub Copy_Filtered_Cells()
Dim from As Excel.Range
Set from = Sheets("Sheet2").Range("I16831:I20610")
Dim too As Excel.Range
Set too = Sheets("Sheet2").Range("J4:J16821") 'Application.InputBox("J4:J16821", Type:=8)
Dim Cell As Excel.Range
For Each Cell In from
Cell.Copy
Dim thing As Excel.Range
For Each thing In too
If thing.EntireRow.RowHeight > 0 Then
thing.PasteSpecial
Set too = thing.Offset(1).Resize(too.Rows.Count)
Exit For
End If
Next
Next
End Sub

Remove reference errors autmatically

i have designed a few codes to help remove reference errors however it does not automatically delete until i assign the macro to a button. i do not want it that way as it would seem unpleasant when i want to present the programme to my team members, and having to remove the errors on the spot with a button. I thought of combining my delete cells code and remove reference cell codes together so that they would run simultaneously but to no avail. Is it possible to combine these two codes to achieve my objective or are there any solutions or coding to remove/hide reference errors automatically? Here are the two codes. All of your help would be very much appreciated!
Sub deletetry2()
Dim R As Range
Set rng = Nothing
On Error Resume Next
Set R = Application.InputBox("Select cells To be deleted", Type:=8)
If TypeName(R) <> "Range" Then
Exit Sub
Else
R.Delete
End If
End Sub
Sub Check_ReferenceDeletecolumn()
Dim rng As Range
Dim rngError As Range
Set rng = Sheets("Sheet3").Range("A1:G100")
On Error Resume Next
Set rngError = rng.Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If Not rngError Is Nothing Then
rngError.EntireColumn.Delete
'delete means cells will move up after deleting that entire row
End If
End Sub
If the objective is to remove all rows containing errors, from a user defined range, this should work:
Option Explicit
Public Sub cleanUserDefinedRange()
Dim response As Range
On Error Resume Next
Set response = Application.InputBox("Select range to clean up errors", Type:=8)
If Not response Is Nothing Then cleanUpErrors response
On Error GoTo 0
End Sub
'------------------------------------------------------------------------------------------
Private Sub cleanUpErrors(ByRef rng As Range)
Application.ScreenUpdating = False
rng.SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Delete
Application.ScreenUpdating = True
End Sub

Writing a string to a cell in excel

I am trying to write a value to the "A1" cell, but am getting the following error:
Application-defined or object-defined error '1004'
I have tried many solutions on the net, but none are working. I am using excel 2007 and the file extensiton is .xlsm.
My code is as follows:
Sub varchanger()
On Error GoTo Whoa
Dim TxtRng As Range
Worksheets("Game").Activate
ActiveSheet.Unprotect
Set TxtRng = ActiveWorkbook.Sheets("Game").Cells(1, 1)
TxtRng.Value = "SubTotal"
'Worksheets("Game").Range("A1") = "Asdf"
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.number
Resume LetsContinue
End Sub
Edit: After I get error if I click the caution icon and then select show calculation steps its working properly
I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.
Try this:
Sub varchanger()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
'or ws.Unprotect Password:="yourpass"
ws.Unprotect
Set TxtRng = ws.Range("A1")
TxtRng.Value = "SubTotal"
'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
' or ws.Protect Password:="yourpass"
ws.Protect
End Sub
If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.
NOTES:
I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.
I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:
Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"
Does this fail as well?
Looks like you tried something similar:
'Worksheets("Game").Range("A1") = "Asdf"
However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.
replace
Range("A1") = "Asdf"
with
Range("A1").value = "Asdf"
try this instead
Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")
ADDITION
Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.
Please can you try the following:
Save a new xlsm file and call it "MyFullyQualified.xlsm"
Add a sheet with no protection and call it "mySheet"
Add a module to the workbook and add the following procedure
Does this run?
Sub varchanger()
With Excel.Application
.ScreenUpdating = True
.Calculation = Excel.xlCalculationAutomatic
.EnableEvents = True
End With
On Error GoTo Whoa:
Dim myBook As Excel.Workbook
Dim mySheet As Excel.Worksheet
Dim Rng As Excel.Range
Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
Set mySheet = myBook.Worksheets("mySheet")
Set Rng = mySheet.Range("A1")
'ActiveSheet.Unprotect
Rng.Value = "SubTotal"
Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.Number
GoTo LetsContinue
End Sub