VBA for performing action until cell meets criteria - vba

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!

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.

Locking "visible" conditionally formatted cells within a named range

Overview
I'm trying to lock cells within a named range that have visible conditional formatting. The 3 linked images below will illustrate my constraints:
Name range: table (cells C1:E6) is set to be conditionally formatted with a blue fill color.
This is the conditional format fill color (color index #: 37) being used.
The row will change to the blue fill if criteria in column A is met, i.e. if the corresponding row in column A has the letter "f" as input.
In summary, I'm trying to lock the rows with the visible blue fill within the named range as well as the rest of the worksheet. And, I only want to edit cells within the named range that don't have the visible blue fill conditional format.
My Solution (so far)...
This macro creates the named range mentioned above and used in LockCells() macro (which is below this code snippet):
Sub NameRange()
'Create named range
Dim rng As Range
Dim range_name As String
Dim cells As String
Dim wkst As String
'Target worksheet
wkst = "Sheet1"
'Range of cells
range_name = "table"
cells = "C1:E6"
'Creates named range
Set rng = Worksheets(wkst).Range(cells)
ThisWorkbook.Names.Add Name:=range_name, RefersTo:=rng
End Sub
This macro loops through cells in named range (table) and attempts to lock the visible blue conditional formatted rows in named range:
Sub LockCells()
'Loop through cells in a given named range
'and lock cells based on blue fill color
Dim cell As Range
Dim color_index As Integer
'Target fill color
color_index = 37
'Target worksheet to protect
wkst = "Sheet1"
'Loop through cells in named range
For Each cell In Range("table")
Dim color As Long
color = cell.FormatConditions(1).Interior.ColorIndex
If (color = color_index) Then
cell.Locked = False
Else
cell.Locked = True
End If
Next
Sets protection for worksheet
Worksheets(wkst).Protect
End Sub
Problem
I'm stuck because instead of locking the visible blue filled cells, and keeping the other cells unlocked for editing, in the named range table it locks all of cells. Mind you, I do want the rest of the worksheet outside of the named range to be locked and protected. I know it's because the conditional format is applied to the named range and evaluating as true. Which is why it locks all cells in named range. My question about solving this issue is below.
Question
Is there state (or visibility) property for conditionally formatted cells?
I was thinking if there is such a property, I could use it in the if statement of my LockCells() macro. E.g. If (color = color_index) & [Conditional Format Visible] Then...
Your help would be much appreciated.
Thank you. :)
Here is a simplified example to work from. I have one format condition which happens to be Cell Value = 2 so I can refer to that rule via .FormatConditions(1) And as the rule is "=" I can use the comparison I have. You would want to adapt to the formula you are using.
Code:
Sub test()
Dim curr As Range
ActiveSheet.Cells.Locked = False
For Each curr In ActiveSheet.Range("C1:E6")
With curr.FormatConditions(1)
If curr.Value = Evaluate(.Formula1) Then curr.Locked = True
End With
Next curr
For Each curr In ActiveSheet.Range("C1:E6")
Debug.Print curr.Address & " locked = " & curr.Locked
Next curr
End Sub
Conditional format rule:
Sheet:
Reference:
http://www.excelfox.com/forum/showthread.php/338-Get-Displayed-Cell-Color-(whether-from-Conditional-Formatting-or-not)

Excel VBA - Capitalizing all selected cells in a column with formulas

I used the code from Siddharth Rout on the following thread to capitalize selected columns but ran into a Error '13' MISMATCH when I used it on a column with cells that had formulas in some of the range.
Excel VBA - Capitalizing all selected cells in column on double click
Here is the code that worked on non-formula based column data from the above link:
Sub ChangeToUpper()
Dim rng As Range
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
End If
Set rng = Selection
rng = WorksheetFunction.Transpose(Split(UCase(Join( _
WorksheetFunction.Transpose(rng), vbBack)), vbBack))
End Sub
I searched the forums and didn't find specifics related to this. So I googled it and Mr.Excel had this code but still gave the Error '13', when I cleared out of the error message everything was capitalized. Is there a way to eliminate getting this error?
Here is the code from Mr.Excel:
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
If Len(cell) > 0 Then cell = UCase(cell)
Next cell
Application.ScreenUpdating = True
End Sub
Check If Cell has formula and or errors, If yes then ignore.
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
'/ Exclude errors
If Not IsError(cell) Then
If Len(cell) > 0 And Not cell.HasFormula Then
cell = UCase(cell)
End If
End If
Next cell
Application.ScreenUpdating = True
End Sub

How to highlight empty/blank cells using VBA macro

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.

Does there exist a VBA command which does not change the formula of a cell, but its value?

Suppose in a worksheet the formula of R4 cell is =B1+B2, and its current value is 10.
A VBA command Range("R4").Value = 5 will change both its formula and its value to 5.
Does anyone know if there exists a VBA command which changes the value of R4 to 5, but does not change its formula, such that its formula is still =B1+B2?
PS: we can also achieve the same state in another way: 1) do a Range("R4").Value = 5 2) change the formula of R4 to =B1+B2 but without evaluating it. In this case, does there exist a VBA command which change the formula of a cell without evaluating it?
Edit: What I want to do is...
I would like to write a function, which takes a worksheet where some cells may be out of date (the formula does not match its value), and generates automatically a VBA Sub, this VBA Sub can reproduce this worksheet. The VBA Sub may look like:
Sub Initiate()
Cells(2,3).Value = 5
Cells(4,5).Value = 10
...
Cells(2,3).Formula = "=2+3"
Cells(4,5).Formula = "=C2+C2"
...
End Sub
Such that running Initiate() builds one worksheet with same values and formulas.
Without the VBA command I am asking, this Initiate() will be hard to generated.
You cannot change the value of a cell to something different than what the cell formula computes to.
Regarding your p.s.: You can probably change the formula of a cell without re-evaluation by changing the calculation mode to manual. But that would of course apply to the entire workbook, not just this one cell
EDIT: maybe a solution would be to temporarily save the formula of the cell in either a tag of that cell, or a hidden worksheet?
It is quite simple to change the result of a formula without changing the formula itself:
Change the value of of its argument(s). This is a Solver-type approach:
Sub ForceDesiredResult()
Dim r As Range
Set r = Range("B2")
With r
If r.HasFormula Then
.Formula = .Formula & "-5"
Else
.Value = .Value - 5
End If
End With
End Sub
Here is some very dirty code that will save all values of all formulas on the active sheet as custom properties of the sheet, and a 2nd sub that will mark red all cells where the value has changed from it's original value, while preserving all formulas. It will need some error-checking routines (property already exists, property doesn't exist,...) but should give you something to work with. Since I don't really understand your problem it's a bit hard to say ;)
Sub AddCustomProperty()
Dim mysheet As Worksheet
Dim mycell2 As Range
Dim myProperty As CustomProperty
Set mysheet = ActiveWorkbook.ActiveSheet
For Each objcell In mysheet.UsedRange.Cells
Debug.Print objcell.Address
If objcell.HasFormula Then Set myProperty = mysheet.CustomProperties.Add(objcell.Address, objcell.Value)
Next objcell
End Sub
Sub CompareTags()
Dim mysheet As Worksheet
Dim mycell2 As Range
Dim myProperty As CustomProperty
Set mysheet = ActiveWorkbook.ActiveSheet
For Each objcell In mysheet.UsedRange.Cells
Debug.Print objcell.Address
If objcell.HasFormula Then
On Error Resume Next
If mysheet.CustomProperties(objcell.Address).Value <> objcell.Value Then
objcell.Font.ColorIndex = 3
On Error GoTo 0
End If
End If
Next objcell
End Sub