Looping through each cell in a Range - vba

I was writing a program for deleting a row in a Selection with Empty Cell. I wrote the code and it worked well but it have a deficiency.
Code Is:
Dim i As Integer
Dim j As Integer
Dim Num As Integer
Num = Selection.Cells.Count
'MsgBox ("Num of Cells " & Num)
Selection.End(xlUp).Select
If (IsEmpty(ActiveCell)) Then
Selection.End(xlDown).Select
End If
For i = 1 To Num
If (IsEmpty(ActiveCell)) Then
ActiveCell.Offset(1, 0).Select
ActiveCell.Offset(-1, 0).EntireRow.Delete
ActiveCell.Offset(-1, 0).Select
Num = Num - 1
On Error GoTo Last
Else
ActiveCell.Offset(1, 0).Select
End If
Next
Last:
Exit
Now I was trying to rewrite the code with looping the cell in Range instead of above For loop:
Dim i As Integer
Dim j As Integer
Dim Num As Integer
Dim myRange As Range
ActiveSheet.Select
Set myRange = Selection.Cells
For Each myRange In Selection
If (IsEmpty(myRange)) Then
ActiveCell.EntireRow.Delete
On Error GoTo Last
Else
'ActiveCell.Offset(1, 0).Select
End If
Next myRange
Last:
Exit
This piece of code is not working Properly. Kindly put your Suggestions and rectify the Code

you could try
If WorksheetFunction.CountBlank(Selection) > 0 Then Intersect(Selection.SpecialCells(xlCellTypeBlanks).EntireRow, Selection.Columns(1)).EntireRow.Delete

Speciealcells seems to be easy to use.
Sub test()
Dim rngDB As Range
Set rngDB = Selection
On Error Resume Next
Set rngDB = rngDB.SpecialCells(xlCellTypeBlanks)
If Err.Number = 0 Then
rngDB.EntireRow.Delete
End If
End Sub

Here is an option that avoids relying on Selection and Select.
You can use a InputBox to determine the range. This will allow you to properly qualify all of your ranges/worksheets. You can then loop through the selected range and determine if the rows should be deleted (if blank).
At the end, delete all the rows at once. On larger operations, this will be much faster since you will only have 1 instance of deletion rather continuously deleting rows in the loop.
Option Explicit
Sub Blanks()
Dim MyRange As Range, MyCell As Range, DeleteMe As Range
Set MyRange = Application.InputBox("Select Range", Type:=8)
For Each MyCell In MyRange
If MyCell = "" Then
If DeleteMe Is Nothing Then
Set DeleteMe = MyCell
Else
Set DeleteMe = Union(DeleteMe, MyCell)
End If
End If
Next MyCell
If Not DeleteMe Is Nothing Then DeleteMe.EntireRow.Delete
End Sub

Related

insert entire same row beneath when condition was met

I am working on the below code to insert same entire row below/beneath original one. I had a hard time fulfilling the requirement because I am just new to making macros.
I already tried searching but not able to code correctly. It is working to insert an empty row. But what I need is to insert the row that met the condition. Below is the screenshot/code for my macro.
Private Sub CommandButton1_Click()
Dim rFound As Range, c As Range
Dim myVals
Dim i As Long
myVals = Array("LB") '<- starts with 51, VE etc
Application.ScreenUpdating = False
With Range("F1", Range("F" & Rows.Count).End(xlUp))
For i = 0 To UBound(myVals)
.AutoFilter field:=1, Criteria1:=myVals(i)
On Error Resume Next
Set rFound = .Offset(2).Resize(.Rows.Count - 1) _
.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
.AutoFilter
If Not rFound Is Nothing Then
For Each c In rFound
Rows(c.Row + 1).Insert
c.Offset(1, -1).Value = ActiveCell.Value
Next c
End If
Next i
End With
Application.ScreenUpdating = True
End Sub
Sub Test()
Dim rng As Range
Dim rngData As Range
Dim rngArea As Range
Dim rngFiltered As Range
Dim cell As Range
Set rng = Range("A1").CurrentRegion
'Exclude header
With rng
Set rngData = .Offset(1).Resize(.Rows.Count - 1)
End With
rng.AutoFilter Field:=6, Criteria1:="LB"
Set rngFiltered = rngData.Columns("F:F").SpecialCells(xlCellTypeVisible)
rng.AutoFilter Field:=6
For Each rngArea In rngFiltered.Areas
For Each cell In rngArea
'// When inserting a row,
'// iteration variable "cell" is adjusted accordingly.
Rows(cell.Row + 1).Insert
Rows(cell.Row).Copy Rows(cell.Row + 1)
Next
Next
End Sub
Below is the code I just used . Thank you!
Private Sub CommandButton2_Click()
Dim x As Long
For x = ActiveSheet.UsedRange.Rows.CountLarge To 1 Step -1
If Cells(x, "F") = "LB" Then
Cells(x, "F") = "ComP"
Cells(x + 1, "F").EntireRow.Insert
Cells(x, "F").EntireRow.Copy Cells(x + 1, "F").EntireRow
End if
Next x
End Sub

How to delete empty cells in excel using vba

This is just a sample I am testing the code in this data. I have three columns in sheet2. I have to delete the empty cells. This is the updated code which is working for column B only. You can check the snapshot
Sub delete()
Dim counter As Integer, i As Integer
counter = 0
For i = 1 To 10
If Cells(i, 1).Value <> "" Then
Cells(counter + 1, 2).Value = Cells(i, 1).Value
counter = counter + 1
End If
Next i
End Sub
Sample screenshot
If all you want is to delete the empty cells, give this a try...
Sub DeleteBlankCells()
Dim rng As Range
On Error Resume Next
Set rng = Intersect(ActiveSheet.UsedRange, Range("A:C"))
rng.SpecialCells(xlCellTypeBlanks).Delete shift:=xlUp
End Sub
Not the most elegant solution but it works.
Option Explicit
Sub delete()
Dim rCells As Range, rCell As Range, sFixCell As String
Set rCells = Range("A1:A13")
For Each rCell In rCells
If rCell = "" Then
sFixCell = rCell.Address
Do While rCell.Value = ""
rCell.delete Shift:=xlUp
Set rCell = Range(sFixCell)
Loop
End If
Next rCell
End Sub

Find and select first blank cell in column B with Excel vba

The below code works fine to find the first empty cell in a given column (here column B). But what I need is a code to find the first blank cell in that column.
Sub macro1()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 2 'column B has a value of 2
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Select
End If
Next
End Sub
Also, it should start looking from row 10 instead of row 1.
Can somebody rewrite this code to do this?
Could something like this be what you're looking for:
Sub test()
Dim ws As Worksheet
Set ws = ActiveSheet
For Each cell In ws.Columns(2).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
End Sub
This will run through each cell in column B in the active worksheet and select the first empty one it comes across. To set the sheet to a particular one Change Set ws = ActiveSheet to Set ws = Sheets("EnterSheetNameHere")
Or you could try using:
Sub test()
Dim ws As Worksheet
Set ws = ActiveSheet
For Each cell In ws.Columns(2).Cells
If Len(cell) = 0 Then cell.Select: Exit For
Next cell
End Sub
My problem is solved by using the following code.
Sheets("sheet1").Select
Dim LR2 As Long, cell2 As Range, rng2 As Range
With Sheets("sheet1")
LR2 = .Range("B" & Rows.Count).End(xlUp).Row
For Each cell2 In .Range("B8:B" & LR2)
If cell2.Value <> "" Then
If rng2 Is Nothing Then
Set rng2 = cell2
Else
Set rng2 = Union(rng2, cell2)
End If
End If
Next cell2
rng2.Select
End With
Just my two cents.
The function will look for the first encountered BLANK cell in a range, so it should work with columns and rows.
'Find first BLANK cell in a given range, returnt a range (one cell)
Function FirstBlank(ByVal rWhere As Range) As Range
Dim vCell As Variant
Dim answer As Range
Set answer = Nothing
For Each vCell In rWhere.Cells
If Len(vCell.Formula) = 0 Then
Set answer = vCell
Exit For
End If
Next vCell
Set FirstBlank = answer
End Function
And then do whatever you want with the cell.
Try this code to select the first empty cell below cell B10. But it requires B10 and B11 to be pre-occupied.
Range("B10").End(xlDown).Offset(1, 0).Select
or
Range("B100000").End(xlUp).Offset(1, 0).Select

In Excel VBA how do I save the selections I have made thorugh my Macro?

I want to select every column that has the word "TEST" in the 5th row range, and then select the cells below down to a certain amount.
I have can find and select the range I want, I just cant have all my selections when I finish, and I want them so I can do some conditional formatting.
Public Sub Macro1()
Dim n As Integer
n = 5
For Each c In Worksheets("Sheet1").Range("E5:UM5").Cells
If InStr(1, "TEST", "TEST") Then
Range(Cells(6, n), Cells(48, n)).Select
n = n + 1
End If
Next
End Sub
Do you think a array would help me to keep the data to then select after?
The code below is modified from user ooo answer here .
Is there a reason you need to select cells? In vba you can do most things without actually selecting cells which makes it quicker and less prone to errors.
If you do need to select the cells I would build up the range and then select it all at once at the end.
Gordon
Sub test()
Dim rng1 As Range
Dim rng2 As Range
Dim newRng As Range
With Sheet1
Set rng1 = .Range("A1:A3")
Set rng2 = .Range("C3:C5")
Set newRng = Union(rng1, rng2)
set rng2 = .range("E5:E7")
set newRng = Union(newRng,rng2)
newrng.select
End With
End Sub
Applied to your code
Public Sub Macro1()
Dim n As Integer
dim rng as range
n = 5
For Each c In Worksheets("Sheet1").Range("E5:UM5").Cells
If InStr(1, "TEST", "TEST") Then
If rng Is Nothing Then
Set rng = Range(Cells(6, n), Cells(48, n))
else
set rng = union(rng, range(cells(6,n),cells(48,n)))
end if
n = n + 1
End If
Next
rng.select
End Sub
Public Sub Macro1()
Dim n As Integer, rng as Range, sht as WorkSheet
Set sht = Worksheets("Sheet1")
For Each c In sht.Range("E5:UM5").Cells
If c.value Like "*TEST*" Then
If rng is nothing then
Set rng = c.offset(1,0).Resize(43,1)
else
Set rng = Application.union(rng, c.offset(1,0).Resize(43,1))
end if
End If
Next
rng.select
End Sub
Public Sub Macro1()
Dim c As Range, rng As Range, ws As Worksheet
Set ws = Worksheets("Sheet1")
For Each c In ws.Range("E5:UM5").Cells
If InStr(c, "TEST") Then
If rng Is Nothing Then
Set rng = c
Else
Set rng = Application.Union(rng, c)
End If
End If
Next
If Not rng Is Nothing Then
rng.Select
Debug.Print rng.Address
Else
Debug.Print "Not found"
End If
End Sub

Remove cells in Excel which have zero values

I have been trying to remove/hide cells which values are equal to zero (0).
Sub HideRows()
Dim cell As Range, rng As Range
Cells.Rows.Hidden = False
On Error Resume Next
Set rng = Columns(5).SpecialCells(xlConstants, xlNumbers)
On Error GoTo 0
For Each cell In rng
If cell.Value = 0 Then
cell.EntireRow.Hidden = True
End If
Next
End Sub
The code removes the entire row. I want to remove the description of the value and the value.
This code will quickly clear (erase) values and comments from cells in column E that have a value of 0
Sub Testme()
Dim rng1 As Range
Set rng1 = Columns(5)
With rng1
.AutoFilter 1, "0"
With rng1.Offset
.ClearContents
.ClearComments
End With
With rng1.Offset(0, -1)
.ClearContents
.ClearComments
End With
End With
End Sub