How to highlight empty/blank cells using VBA macro - vba

I realized I messed up asking my very first question, so I will try one last time. I am targeting the same 4 columns from 2 separate sheets that have cells that either contain text or do not. Sheet 1 will be updated automatically, so I will be running this code daily to manually update sheet 2. I am trying to find a way to basically find out which cells are missing the text using a macro. I tried using a code that I found on this website that puts borders on cells containing text and clears borders for empty cells.
Sub BorderForNonEmpty()
Dim myRange As Range
Set myRange = Sheet1.Range("C2:C252")
' Clear Existing Borders
myRange.Borders.Linestyle = xlLineStyleNone
' Test Each Cell and Put a Border Around it if it has content
For Each myCell in myRange
If myCell.Text <> "" Then
myCell.BorderAround (xlContinuous)
End If
Next
End Sub
This code works, but I want to try to highlight the empty cells with a color opposed to clearing its border. This is also my first time posting on StackOverflow, so I apologize beforehand. Thank you.

Instead of looping through all cells, Excel has a built in function to select blank Cells. This should be faster, and more reliable.
Sub BorderForNonEmpty()
Dim myRange As Range
Set myRange = Sheet1.Range("C2:C252")
'clear all color
myRange.Interior.ColorIndex = xlNone
'color only blank cells
myRange.SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 6
End Sub
Another option could be to just use conditional formatting (another built-in feature), but that can be hard to control for changing ranges.

Replace
myCell.BorderAround (xlContinuous)
with
myCell.Interior.Color = RGB(100, 100, 100)

Give this a try:
Sub BorderForNonEmpty()
Dim myRange As Range
Set myRange = Sheet1.Range("C2:C252")
For Each myCell In myRange
If myCell.Text = "" Then
myCell.Interior.ColorIndex = 6
End If
Next
End Sub
EDIT#1:
Sub BorderForNonEmpty()
Dim myRange As Range
Set myRange = Sheet1.Range("C2:C252")
For Each myCell In myRange
If myCell.Text = "" Then
myCell.Interior.ColorIndex = 6
Else
myCell.Interior.ColorIndex = xlNone
End If
Next
End Sub
EDIT#2:
To make the macro "clickable":
Put any AutoShape on the worksheet
Format the AutoShape
Right-click the AutoShape and assign the macro to it.

Related

VBA - Highlight Cell With Checkbox

Some logic to my process:
In column K on my worksheet I have inserted check boxes from cell K3 - K53 (this could become longer in the future) using the developer tab.
I then associated the check box with the same cell it is placed in.
I formatted the cells in this column by going to 'Format Cells', clicking on 'Custom' then typing in ';;;'. This was to HIDE the 'True/False' text from view.
My next step is to change the cell colour based on the text.
Note:
I have searched through a few forums and combined some code samples from them all, so I will not be able to reference the sources exactly, but below is what I have so far:
Code:
Sub Change_Cell_Colour()
Dim xName As Integer
Dim xChk As CheckBox
Dim rng As Range
Dim lRow As Long
lRow = ActiveWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
Set rng = ActiveWorksheet.Range("K2:K" & lRow)
For Each xChk In ActiveSheet.CheckBoxes
xName = Right(xChk.Name, Len(xChk.Name) - 10)
If (Range(xChk.LinkedCell) = "True") Then
rng.Interior.ColorIndex = 6
Else
rng.Interior.ColorIndex = xlNone
End If
Next
End Sub
I keep getting an error on the line where I try to get the last row.
Code:
lRow = ActiveWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
Error:
Object Required
I am not even sure if the code I have will solve my issue, so any help solving the main issue highlighting a cell based on the check box being checked or not, will be greatly appreciated.
Here's a quick rewrite with LOTS of comments explaining:
Sub Change_Cell_Colour()
Dim xChk As CheckBox
'Be explicit about which worksheet. Leaving it to "Activeworksheet" is going to cause problems
' as we aren't always sure which sheet is active...
'Also in this case we don't need to know the last row. We will iterate checkbox objects, not
' populate rows.
'lRow = ActiveWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
'Again... we don't need this. We just need to iterate all the checkboxes on the sheet
'Set rng = ActiveWorksheet.Range("K2:K" & lRow)
'This is good stuff right here, just change the ActiveSheet to something more explicit
' I've changed this to the tab named "Sheet1" for instance.
For Each xChk In Sheets("Sheet1").CheckBoxes
'Getting the name of the checkbox (but only the last 10 characters)
xName = Right(xChk.Name, Len(xChk.Name) - 10)
'We can check the linked cell's value, but we can also just check if the
' if the checkbox is checked... wouldn't that be easier?
'If (Range(xChk.LinkedCell) = "True") Then
If xChk.Value = 1 Then
'Now we can use the "LinkedCell", but it's a STRING not a RANGE, so we will have
' to treat it as the string name of a range to use it properly
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = 6
Else
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = xlNone
End If
Next
End Sub
Here's the barebones version just to get it working
Sub Change_Cell_Colour()
Dim xChk As CheckBox
'Loop through each checkbox in Sheet1. Set it to color 6 if true, otherwise no color
For Each xChk In Sheets("Sheet1").CheckBoxes
If xChk.Value = 1 Then
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = 6
Else
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = xlNone
End If
Next
End Sub
I'm totally assuming here, but I would imagine you want this macro to fire when a checkbox is clicked. There is a handy Application.Caller that holds the name of the object that caused a macro to be called. You can set the "Assign Macro.." of each checkbox to this new code and then you can figure out which checkbox called the subroutine/macro using application.caller and follow the same logic to toggle it's linked cell color:
Sub Change_Cell_Colour()
Dim xChk As CheckBox
'Who called this subroutine/macro?
Dim clickedCheckbox As String
clickedCheckbox = Application.Caller
'Lets check just this checkbox
Set xChk = Sheets("Sheet1").CheckBoxes(clickedCheckbox)
'toggle its color or colour if you are a neighbour
If xChk.Value = 1 Then
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = 6
Else
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = xlNone
End If
End Sub
highlighting a cell based on the check box being checked or not
Select the sheet and apply a CF formula rule of:
=A1=TRUE
ActiveWorksheet doesn't exist, and because you haven't specified Option Explicit at the top of your module, VBA happily considers it an on-the-spot Variant variable.
Except, a Variant created on-the-spot doesn't have a subtype, so it's Variant/Empty.
And ActiveWorksheet.Cells being syntactically a member call, VBA understands it as such - so ActiveWorksheet must therefore be an object - but it's a Variant/Empty, hence, object required: the call is illegal unless ActiveWorksheet is an actual Worksheet object reference.
Specify Option Explicit at the top of the module. Declare all variables.
Then change ActiveWorksheet for ActiveSheet.

VBA for performing action until cell meets criteria

I've had no luck on searching this, I hope you all can help.
I am trying to perform the following in Excel:
If a cell matches a value from table1, highlight that cell. Then highlight the cell below it and continue to highlight the cells below it until it reaches a cell that matches a value from table2.
I cant figure out how to work in the loop function for this
Thanks in advance
I've written a simple for loop, which iterates through the data range. My data table consists of integers 1 - 15, named 'Data'. The starting point is named 'Point_1' and the ending point is named 'Point_2'.
The code is below, annotated for clarity. In essence, it is simply toggling highlight ON when the cell matches Point_1, and highlighting until it is toggled back OFF, when the cell matches Point_2.
Sub HighlightRange()
Dim cel As Range
Dim dataRange As Range
Dim highlighting As Boolean
highlighting = False
With Application.ActiveWorkbook.Sheets("Sheet1")
Set dataRange = .Range("Data") 'This is your data range. I named mine 'Data'
For Each cel In dataRange
'Check for beginning or end values
If cel = .Range("Point_1").Value Then 'This is your starting value. I named mine 'Point_1'
highlighting = True
ElseIf cel = .Range("Point_2").Value Then 'This is your ending value. I named mine 'Point_2'
highlighting = False
End If
'While highlighting is activated, highlight the current cell
If highlighting = True Then
cel.Interior.ColorIndex = 5
End If
Next cel 'Check all cells in dataRange
End With
End Sub
Notably, the end point is not highlighted. However, you can move the ElseIf statement that turns highlighting back off to the end of the for loop, after the highlight command. This will turn highlighting off AFTER highlighting Point_2 instead of just before. Code for this case is below.
Sub HighlightRange()
Dim cel As Range
Dim dataRange As Range
Dim highlighting As Boolean
highlighting = False
With Application.ActiveWorkbook.Sheets("Sheet1")
'This code also highlights Point_2.
Set dataRange = .Range("Data") 'This is your data range. I named mine 'Data'
For Each cel In dataRange
'Check for beginning or end values
If cel = .Range("Point_1").Value Then 'This is your starting value. I named mine 'Point_1'
highlighting = True
End If
'While highlighting is activated, highlight the current cell
If highlighting = True Then
cel.Interior.ColorIndex = 5
End If
If cel = .Range("Point_2").Value Then 'This is your ending value. I named mine 'Point_2'
highlighting = False
End If
Next cel 'Check all cells in dataRange
End With
End Sub
I hope this helped! You can change the highlight color from blue (colorIndex = 5) to whatever color you like. If you click Record Macro and format a cell just how you want, you can copy the generated code into this macro in place of the following line:
cel.Interior.ColorIndex = 5
Cheers and Good Luck!

Delete a row based on conditional value fill

I am currently working on a database analysis and I have a Conditional format rule which fills a cell red. I need to delete the whole row for that cell which is red, I am able to do so if the cell is filled with that color manually but not through the conditional value rule, Here is what I have right now:
Sub delteRed()
Dim xRg As Range, rgDel As Range
Sheets("Hoja1").Select
For Each xRg In ThisWorkbook.ActiveSheet.Range("A2:A21")
If xRg.Interior.ColorIndex = 3 Then
If rgDel Is Nothing Then
Set rgDel = xRg
Else
Set rgDel = Union(rgDel, xRg)
End If
End If
Next xRg
If Not rgDel Is Nothing Then rgDel.EntireRow.Delete
End Sub
In a VBA sub procedure you can use the DisplayFormat to determine the color of a cell that has been adjusted by a CFR.
If xRg.DisplayFormat.Interior.ColorIndex = 3 Then
DisplayFormat cannot be used in a UDF.

Save selection at beginning of macro and set it to be the same at the end of macro?

I have a macro that selects things in a sheet.
Prior to running the main section of the macro I want to save the active selection, so that I can set the same selection at the end of the macro.
I've tried the solution below, but it doesn't work. I'd appreciate suggestions.
Dim rng As Range
'Beginning of macro
rng = Range(ActiveSheet.Selection) 'Object doesn't support this property or method
'Main section
'End of macro
rng.Select
Solution offered by tmoore82 is the best way to go (+1)
For completeness you can also save the Address as a string:
Dim selectionAddress as String
selectionAddress = Selection.Address 'e.g. A1 is "$A$1"
'Your macro
Range(selectionAddress).Select 'At end of macro select cell A1
Instead of rng = Range(ActiveSheet.Selection), it should be Set rng = Selection.

How to delete all row which contains "Grand Total" in Excel automatically?

In my active sheet called Report I have 2 column I & F.
It has repeating cells containing text "Grand Total".
I would like to delete whole row if it contains Grand Total automatically.
VBA code would be nice.
With the following VBA code, you can quickly delete the rows with certain cell value, please do as the following steps:
Select the range that you want to delete the specific row.
Click Developer>Visual Basic, a new Microsoft Visual Basic for applications window will be displayed, click Insert > Module, and input the following code into the Module:
VBA code to Remove entire rows based on cell value(i.e. Grand Total):
Sub Delete_Rows()
Dim rng As Range, cell As Range, del As Range
Set rng = Intersect(Range("A1:D22"), ActiveSheet.UsedRange)
For Each cell In rng
If (cell.Value) = "Grand Total" _
Then
If del Is Nothing Then
Set del = cell
Else: Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.Delete
End Sub
Then click "Play/Run" button to run the code, and the rows which have certain value have been removed.
(Note: If you can't see Developer Tab in Excel Do these Steps: 1)Click the Office Button, and then click Excel Options. 2)In the Popular category, under Top options for working with Excel, select the Show Developer tab in the Ribbon check box, and then click OK.)
Using AutoFilter is very efficient. This can also be done without VBA (ie manually)
Main Sub
Sub Main()
Dim ws As Worksheet
Dim rng1 As Range
Dim StrIn As String
Dim rng2 As Range
Set ws = Sheets("Sheet1")
Application.ScreenUpdating = False
Set rng1 = ws.Range("F:F,I:I")
StrIn = "Grand Total"
For Each rng2 In rng1.Columns
Call FilterCull(rng2, StrIn)
Next
Application.ScreenUpdating = True
End Sub
Delete Sub
Sub FilterCull(ByVal rng2, ByVal StrIn)
With rng2
.Parent.AutoFilterMode = False
.AutoFilter Field:=1, Criteria1:=StrIn
.EntireRow.Delete
.Parent.AutoFilterMode = False
End With
End Sub
This should help get you started.
http://msdn.microsoft.com/en-us/library/office/ee814737%28v=office.14%29.aspx#odc_Office14_ta_GettingStartedWithVBAInExcel2010_VBAProgramming101
Also see similar question:
Delete a row in Excel VBA