Creating a macro to delete rows in Excel using VB - excel

I need a code that will delete the enitre row when a specific name is typed into column A.
So, for each row that has "Surgery" in column A, it needs to be deleted. Thanks.

This should work. All you need to do is change the value of areaToSearch to fit your workbook. Also watch the case on the keyword, "Surgery" and "surgery" are not the same! I tested this and it worked on a sheet I made up.
Option Explicit
Sub DeleteSurgery()
Dim keyWord As String
Dim cell As Range, areaToSearch As Range
keyWord = "Surgery"
Set areaToSearch = Sheet1.Range("A1:A10")
For Each cell In areaToSearch
If cell.Value = keyWord Then
cell.EntireRow.Delete
End If
Next cell
End Sub

Related

find blank cells in columns and replace them with 0, repeat for next row if next row has data

I am using excel userform to input the data. I want for Columns C2:F2, if the user has not inputted any number in it, excel should convert these blanks into 0. And I want it to repeat for the next row when the data for next row is inputted. I tried some simple coding but it didn't work.
Public Sub BlankCells()
Dim rng As Range
rng = Range("C2:C1000", "D2:D1000", "E2:E1000", "F2:F1000")
For Each cell In rng
If cell = "" Then cell.Value = "0"
Next cell
Find
End Sub
It works if use coding for single row only i.e. "C2:F2", but i want it repeat for the next rows as well when the next row gets the data.
When you create a variable for sheet or range, you need to use the Set keyword like this:
Set rng = Range("C2:F1000")
If you'd like to refer to multiple ranges, you can add all the ranges as one comma separated string

Is there a way to not have a blank cell considered 0 in VBA?

New to vba and trying to do something very basic. I have a column full of numbers that also contains blank cells. When I try to do this If statement, Excel considers the blank cells as the value 0. I only want the cells with numbers to have the "Alerted Transaction" value, not the blank cells. Any help is appreciated. Thanks.
If Columns("J").Value > 0 Then Columns("J").Value = "Alerted Transaction"
Define the range you want to check, loop each cell in the range and check for empty cells.
dim myWS As Worksheet
set myWS = ThisWorkbook.Worksheets("myWorksheet")
With myWS
Dim loopRange As Range
set loopRange = .Range(.Cells(2,10),.Cells(.UsedRange.Rows.Count,10))
End with
dim currCell As Range
for each currCell in loopRange
if currCell.Text<>vbNullString Then
currCell.Offset(0,3).Value = "Alerted Transaction"
end if
next
There are better ways to get the last populated cell in a column, but that is for another day :)
For Each c In Worksheets("Sheet1").Range("J1:J10").Cells
If Not IsEmpty(c.Value) Then c.Value = "Alert"
Next
As #BigBen pointed out, you probably don't want to IsEmpty the whole column, this code checks Row 1 to Row 10 in Column J. You may adopt the code to your scenario accordingly.
See doc on IsEmpty and doc on For loop
You can check to see if a cell is empty by using the
IsEmpty function. I don't really mess around with Excel so I don't know how you would check a range of cells.

Selecting an area with exception of merged cells in dynamic range

IMPORTANT EDIT: The main issue here is caused by hidden merged cells that are causing the entirity of their active range to be selected. Unless you know a way how to dynamically skip merged cells (in a dynamic range), the it most likely won't help. Have changed the entirity of question accordingly
any idea what am I doing wrong?
Got the following code, fyi the function find_last_row returns the value of last active row as integer. In this case, the returned variable would be 40
Private Sub initalize_button_Click()
Dim lastRow As Integer
Dim ws As Worksheet: Set ws = Sheets("Training_Planner")
lastRow = find_last_row
With ws
.Activate
.Range("E5:H" & lastRow).Select
End With
End Sub
Pretty basic code, should open the worksheet Training_Planner and select from E5 to HlastRow (in this case lastRow is 40) so the selected range should be E5:H40
Here is the expected result:
What I get instead:
Curiously enough, it selects only active range, but it's as if it didn't pay attention to columns, instead of the expected E5:H40 i get B5:I40
Any idea what's causing this?
Ok, first of all, if your range is gonna start always as E5, your range is 50% dinamic, because it starts always in same column and same row. Your Range is (Cells(a,b),Cells(c,d)), this means a = 5 and b = 5 (Column E).
Also, you say and Inputbox asks users for end cell of range (in your example is H40, but this is dynamic).
So, my code checks EVERY SINGLE cell in the range formed, and then, using Application.UnionI set a final big range. We cannot just use an array to select all of them, because your range is dynamic, and selecting ranges with arrays is limited to 30 args, so we need to update our FinalRange for each cell.
Dim MyCell As Range
Dim RangeWanted As Range
Dim MyFinalRange As Range
Set RangeWanted = Range("E5:" & InputBox("Cell Address")) 'User inputs Final Cell of Range. Start is always E5
'let's get all invididual addresses of each cell inthat dynamic RangeWanted
For Each MyCell In RangeWanted
If MyCell.MergeCells = False Then 'If not merged, we add it to FinalRange
If MyFinalRange Is Nothing Then
Set MyFinalRange = MyCell
Else
Set MyFinalRange = Application.Union(MyFinalRange, MyCell)
End If
End If
Next MyCell
Set RangeWanted = Nothing
MyFinalRange.Select
With this code, from Range("E5:H40") in image,yellow cells are merged. I want to select only the not merged ones. And using this code, I get this:
My example is with Range("E5:H40") but it works also with other ranges.
Try it and adapt the code to your needs.
Whenever something small like this is happening, simply try to simplify as much as you can. In your case, it would be this:
Sub TestMe()
Worksheets("Training_Planner").Range("E5:H40").Select
End Sub
If it selects E5:H40 then everything is ok. If not, try to select it manually. Probably you have a hidden row, which is merged from B to I, thus it is happenning this way.
Instead of this:
.Range("E5:H" & lastRow).Select
Try going with this:
.Range("E5", (Cells(Rows.Count, "H").End(xlUp))).Select
It count all the rows "H" has and then goes up until it finds the first item. And it will then select from "E1" to last item in "H"

Highlighting rows where a cell contains a name from a list of names

How would I go about highlighting rows which contain a cell that contains a name from a list of names which I can specify?
I assume this is best done by a macro, but not sure where to start.
Place this code in a module
Option Explicit
Public Sub ApplyConditionalFormattingsFromAList()
'
' this code create multiple conditional formattings on current selected cells
' using a list of conditions along with its formattings defined in another worksheet.
' to use, just select the range and then run this code
'
Dim iRng As Range
Dim ApplyToRng As Range
Dim wsCondition As Worksheet
' determine the worksheet that define the conditions and formattings
' to do this, create a blank worksheet and name it "Names",
' then in the worksheet,
' column A of the worksheet should contain the names to highlight, start at [A1]
' column B of the worksheet should be filled with the highlight color to apply, working in pair with column A
Set wsCondition = Worksheets("Names")
' i make the Macro to apply to current selection.
' i made it this way so that you can reuse this code on different sheets multiple times
' anyway, you can change this to apply to a fixed range, which can then be turned into automatic running code.
' e.g. Set ApplyToRng = Columns("B")
Set ApplyToRng = Selection
' clear the conditional formattings of current selection. otherwise the list of conditional formatting will keep growing.
ApplyToRng.FormatConditions.Delete
' add the conditions
For Each iRng In wsCondition.Range([A1].Address, wsCondition.Cells(Rows.Count, 1).End(xlUp))
ApplyToRng.FormatConditions.Add Type:=xlTextString, String:=iRng.Value, TextOperator:=XlContainsOperator.xlContains
ApplyToRng.FormatConditions(ApplyToRng.FormatConditions.Count).SetFirstPriority
ApplyToRng.FormatConditions(1).Interior.Color = iRng.Offset(0, 1).Interior.Color
ApplyToRng.FormatConditions(1).StopIfTrue = False
Next iRng
End Sub
The worksheet "Names" would look like this
I would write it as a macro.
Begin with the first sheet.
Find the last used column and the last used row on that sheet.
Use these figures to iterate through each cell in each row.
For each cell you iterate through you need to go to the list and iterate through each item in the list. Compare the cell value and the list value, if they are the same then highlight the row and go the next row.
I hope that helps.

Unmerge cells and distribute contents in Excel (for mac) 2011

I have a spreadsheet with a large amount of data in. About half the cells are merged horizontally with other cells and contain names e.g. John Doe.
Does anyone know how to write a macro to unmerge the cells while distributing the value of the cell to all the cells that were previously merged?
Cheers
Jack
EDIT: The reason I am doing this is to check to see if two adjacent cells are equal i.e. is A1 = A2. But I run into problems when either cell is merged. If anyone knows a way around this problem without separating the cells and copying the data that would be even better!
The idea I provide below is tested for Excel 2010 VBA Win7. However, being not sure I hope it should work as for Mac, too (as this is rather set of standard properties and methods of Range object). If this doesn't work please let me know to delete my answer.
This simple code will work for selected area however it's quite easy to change it to any other range. Some other comment inside the code below.
Sub Unmerging_Selection()
Dim tmpAddress As String
Dim Cell As Range
'change Selection below for any other range to process
For Each Cell In Selection
'check if cell is merged
If Cell.MergeCells Then
'if so- check the range merged
tmpAddress = Cell.MergeArea.Address
'umnerge
Cell.UnMerge
'put the value of the cell to
Range(tmpAddress) = Cell
End If
Next
End sub
And the picture presenting before and after result:
I was able to get the solution from KazJaw to work on a mac with one edit, changing Cell.UnMerge to
ActiveSheet.UsedRange.MergeCells = False, as provided by Ron Debruin here: http://www.rondebruin.nl/mac/mac027.htm.
Sub Unmerging_Selection()
Dim tmpAddress As String
Dim Cell As Range
'change Selection below for any other range to process
For Each Cell In Selection
'check if cell is merged
If Cell.MergeCells Then
'if so- check the range merged
tmpAddress = Cell.MergeArea.Address
'umnerge
ActiveSheet.UsedRange.MergeCells = False
'put the value of the cell to
Range(tmpAddress) = Cell
End If
Next
End sub

Resources