If Cells A1:C1= "No", All cells in the risk of the row will be blocked from input - vba

Anyone know how to block cells from input (also gray it out) if for example cells A1:C1 = "No" then the rest of the row up to a say F1 is grayed out and blocked from input? I was hoping to do this in VBA but if there are other easier ways, please let me know! Thank you!
Didi

Just to show a different approach:
Put this in the sheet-code-tab:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not (Intersect(Target, Me.Range("D1:F1")) Is Nothing) And Me.Evaluate("AND(LOWER(A1:C1)=""no"")") Then Me.Range("A1").Select
End Sub
And to grey them out, best will be conditional formatting:
Range: =$D$1:$F$1
Formula: =AND(LOWER($A$1:$C$1)="no")
Using the conditional formatting allows to change the cells as you like without the need to alter the VBA code (this also will be faster)
The VBA part itself, just sets the selected cell to A1 if A1:C1 is "No" and a range is selected which also includes any of the cells of D1:F1
The LOWER can be skipped if you want it to be case sensitive
The only con is: if A1:C1 is "no" you still can paste a range to a cell (not any of D1:F1 directly) which also include the locked cells.
The biggest pro is: this also works for shared workbooks (as there is no need to lock/unlock sheets)
EDIT
If the cells need to be protected then something like this will do:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim a As Boolean
a = Me.Evaluate("AND(LOWER(A1:C1)=""no"")")
If a <> Me.Range("D1").Locked Then
Me.Unprotect
Me.Range("D1:F1").Locked = a
Me.Protect
End If
End Sub

as was mentioned in the comments, look to use a workbook change event with the following sub
Sub test()
If Worksheets("Sheet1").Range("A1").Value = "no" And Worksheets("Sheet1").Range("B1").Value = "no" And Worksheets("Sheet1").Range("C1").Value = "no" Then
Worksheets("Sheet1").Range("D1:F1").Interior.Color = RGB(220, 220, 220)
Worksheets("Sheet1").Range("D1:F1").Locked = True
Worksheets("Sheet1").Protect
End If
End Sub

Related

Validating Cell Input Based on Another Cell

When I input some text in a cell, for example in cell B2-test, I want in cell A6 the input to begin with this string and to end with _VAR1-for example test_VAR1.
I have found a simple solution as formula - =IF(A2="test","test_VAR1") but I want to make it as a VBA code.
So any idea how this can be done?
This is the most minimal example that I can come up with.
The LCase(Range("B2")) would also take "Test" and "TeSt" into account:
Option Explicit
Public Sub TestMe()
With ActiveSheet
If LCase(.Range("B2")) = "test" Then
.Range("A6") = .Range("B2") & "_VAR1"
End If
End With
End Sub
And if you want to check every event of the worksheet, put your code in the corresponding worksheet (Sheet1, Sheet2 and Sheet3 on the picture below):
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
If Intersect(Target, Me.Range("B2")) Is Nothing Then Exit Sub
Application.EnableEvents = False
If LCase(Target) = "test" Then
Me.Range("A6") = Target & "_VAR1"
End If
Application.EnableEvents = True
End Sub
I know you said in your question you wanted macro, but I'm not going to post my own (because I feel like #Vityata's answer should be sufficient)
However, I got impression from your post, that you could adjust / improve your formula instead and avoid macro altogether. It's usually better to avoid macro, when possible, for compatibility reasons (a lot of users have macros disabled by default)
If you simply want to add the keyword "_VAR1" to the input, use the following formula instead
=LTRIM(B2) & "_VAR1"
If the input can be anything, that contains the word "test"
=IF(ISNUMBER(SEARCH("test", TRIM(LOWER(B2)))), LTRIM(B2) & "_VAR1", "Incorrect Input")
The text contains only the word "test" and nothing else
=IF(TRIM(LOWER(B2))="test", LTRIM(B2) & "_VAR1", "Incorrect input"
There are some other variations / tricks you could do with this, but these are some of the most basic examples you can use as your "building blocks"

Excel macro cell address increase

Can i increase the cell address by using macro?
I'm implementing excel cell color matching function.
Example:
When i change the cell "A1" to red, cell "D1" will change to red.
if change "C1" to red, "F1" will change to red too. All need to increase 3 column.
Now i just need to modify the "c.Address" by + 3 so the cell will go do D1.
I try using c.Address + 3 but it can't work.
Any help will be appreciate!
Thanks!
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
For Each c In Worksheets("Sheet1").Range("A1:C1").Cells
If c.Interior.Color = 255 Then
Sheet1.Range(c.Address + 3 ).Interior.Color = 255 <<-- Can't work
Else
Sheet1.Range(c.Address + 3 ).Interior.Color = white <<-- Can't work
End If
Next c
End Sub
Change this:
Sheet1.Range(c.Address + 3 )
To this
Sheet1.Range(c.Address).offset(0,3)
Although I don't know why you need Sheet1.Range(c.Address) and not just c, is c a range? if so you can just do c.offset(0,3)
I really hoped, that Sixthsense is going to edit his answer so I can give him the +1 but it doesn't look like that will happen :(
Still knowing what he tried to achieve, I will at least show some working code and explain it a bit. So first things first: the code:
Option Explicit
Dim rngHolder As Range
Private Sub Worksheet_Activate()
If rngHolder Is Nothing Then Set rngHolder = Intersect(Selection, Range("A1:C1"))
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not rngHolder Is Nothing Then
Dim rngRunner As Variant
For Each rngRunner In rngHolder.Cells
rngRunner.Offset(0, 3).Interior.Color = IIf(rngRunner.Interior.Color = 255, 255, xlNone)
Next
End If
Set rngHolder = Intersect(Target, Range("A1:C1"))
End Sub
The rngHolder (like the sPrev from Sixthsense) is important, because changing the selection, does not return the "old" selection. If you select A1 and change the color no trigger will be activated, so we are going with the Worksheet_SelectionChange. Now after the change, we select D19 and nothing will tell us that A1 has been changed. But we also do not want to run all changes every time the selection changes. For this reason the "last" selection will be stored inside the rngHolder.
I skipped some parts and directly push the selected ranges which cross the cells we need to look at in the variable (or nothing if no intersect is found).
If rngHolder is not empty the next time we select a different cell, it will run all cells in rngHolder to change the background color of the desired cells 3 columns to the right. (this way also changing multiple cells at once will work) and also push the new intersect in the rngHolder.
To the point which I was complaining about the solution of Sixthsense:
If the first selection you do is ...lets say X7... then selecting A3 afterwards will change the background color of AA7 to the same like X7 has. This may be not noticed due to conditional formatting and stuff like that. Wrong "highlight" however may leed to user-errors later on (you also may notice it at a point lots of cells have allready beed changed)
However, the question was just for the "Offset"-function which is already answered in a proper way ;)
Replace your current code with the below one.
Dim sPrev As String
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If sPrev = "" Then sPrev = Target.Address
If Target.Cells.Count = 1 Then
If Target.Column = Range("A:A").Column Then
With Range(sPrev)
.Offset(, 3).Interior.Color = .Interior.Color
End With
sPrev = Target.Address
End If
End If
End Sub

Change worksheet tab color if range of cells contains text

I have tried code that I've found here on stackoverflow, and elsewhere but they aren't working as I think they can. I'll list them below. I'm almost certain this is an easy question.
What I'm trying to do: If in any of the cells in the range A2:A100 there is any text or number whatsoever, then make the worksheet tab red. And I will need to do this on over 20 tabs. This must execute upon opening the workbook, and thus not require manually changing a cell or recalculating.
The problems I've had with other code: As far as I can tell they require editing a cell, and then quickly hitting enter again. I tried SHIFT + F9 to recalculate, but this had no effect, as I think this is only for formulas. Code 1 seems to work albeit with having to manually re-enter text, but no matter what color value, I always get a black tab color.
Code I've tried:
Code 1:
Private Sub Worksheet_Change(ByVal Target As Range)
MyVal = Range("A2:A27").Text
With ActiveSheet.Tab
Select Case MyVal
Case ""
.Color = xlColorIndexNone
Case Else
.ColorIndex = 6
End Select
End With
End Sub
Code 2: This is from a stackoverflow question, although I modified the code slightly to fit my needs. Specifically, if in the set range there are no values to leave the tab color alone, and otherwise to change it to color value 6. But I'm sure I've done something wrong, I'm unfamiliar with VBA coding.
Private Sub Worksheet_Calculate()
If Range("A2:A100").Text = "" Then
ActiveWorkbook.ActiveSheet.Tab.Color = xlColorIndexNone
Else
ActiveWorkbook.ActiveSheet.Tab.Color = 6
End If
End Sub
Thanks for your help!
I posted this on superuser first, but perhaps stackoverflow is more appropriate since it is explicitly programming-related.
Only two things will be able to switch the condition in this statement:
If Range("A2:A100").Text = "" Then
You've already identified both of them, changing the contents of the one of the cells in that range on a worksheet, or a formula in one of those cells recalculating to or from a value of "". As far as event triggers go, if the formula result changes, both the WorkSheet_Calculate and Worksheet_Change events will fire. Of the two, Worksheet_Change is the one to respond to, because WorkSheet_Calculate will only fire if any of the cells in A2:A100 contain a formula. Not if they only contain values - your "Code 2" isn't wrong, the event was just never firing.
The simple solution is to set your tab colors when you open the workbook. That way it doesn't matter if you have to activate a cell in that range and change it - that's only way the value you're testing against is going to change.
I'd do something like this (code in ThisWorkbook):
Option Explicit
Private Sub Workbook_Open()
Dim sheet As Worksheet
For Each sheet In Me.Worksheets
SetTabColor sheet
Next sheet
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Not Intersect(Target, Sh.Range("A2:A100")) Is Nothing Then
SetTabColor Sh
End If
End Sub
Private Sub SetTabColor(sheet As Worksheet)
If sheet.Range("A2:A100").Text = vbNullString Then
sheet.Tab.Color = xlColorIndexNone
Else
sheet.Tab.Color = 6
End If
End Sub
EDIT: To test for the presence of specific text, you can do the same thing but need to have the test check every cell in the range you're monitoring.
Private Sub SetTabColor(sheet As Worksheet)
Dim test As Range
For Each test In sheet.Range("A2:A100")
sheet.Tab.Color = xlColorIndexNone
If test.Text = "whatever" Then
sheet.Tab.Color = vbRed
Exit For
End If
Next test
End Sub
Maybe test the len of the trimmed joined string of cells:
Private Sub Worksheet_Calculate()
If Len(Trim(Join(Application.Transpose(Range("A2:A100"))))) = 0 Then
ActiveWorkbook.ActiveSheet.Tab.Color = xlColorIndexNone
Else
ActiveWorkbook.ActiveSheet.Tab.Color = 6
End If
End Sub
This code will fire off every time the sheet calculates though as it is event code, I am not sure if that is what you want? If not then post back and we can drop it into a normal sub for you and make it poll all the sheets to test.
Worksheet_Change function will get called everytime there's change in the target range. You just need to place the code under Worksheet. If you have placed the code in the module or Thisworkbook then it wont work.
Paste the below in Sheet1 of your workbook and check if it works. Of Course you will need to do modification to the below code as I have not written complete code.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim WatchRange As Range
Dim IntersectRange As Range
Set WatchRange = Range("A1:A20")
Set IntersectRange = Intersect(Target, WatchRange)
If IntersectRange Is Nothing Then
''Here undo tab color
Else
ActiveSheet.Tab.ColorIndex = 6
End If
End Sub

Use VBA to render cell containing drop down list, read only if range has value

how do I, using VBA, make a G1 read only if any cell in a range say like A4:E50 has a value? My intent is to disable the option in G1 which is a drop down list, as soon as the user populates any of the cells in range A4:E50. If the users deletes all the values in the range, only then will the options in G1 be available. How do i achieve this?
This is a quick solution I just came up with... Not pretty, but it'll do the trick:
First run this macro just once:
Sub LockOneTime()
ActiveSheet.Cells.Locked = False
ActiveSheet.Range("G1").Locked = True
End Sub
Then put this in your worksheet code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.WorksheetFunction.CountA(Range("A1:E40")) > 0 Then
ActiveSheet.Protect contents:=True
Else
ActiveSheet.Protect contents:=False
End If
End Sub
It's a quick and dirty way to get what you're looking to achieve...
EDIT Based upon Other cells being Locked:
Given you can't use worksheet protection to avhieve your goal, just put this code in your worksheet's code module (You no longer need the first LockOneTime macro):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not (Intersect(Target, Range("G1")) Is Nothing) Then
If Application.WorksheetFunction.CountA(Range("A4:E50")) > 0 Then
Application.EnableEvents = False
MsgBox "You cannot change the value in cell G1"
Application.Undo
Application.EnableEvents = True
End If
End If
End Sub
This won't let a change happen to cell G1, BUT its draw-back is, assuming you changed a lot of cells and G1 was one of them, it won't let any changes happen... In other words, if G1 is one of the cells being changed, then none of the cells will be allowed to be changed.
Hope this is ok by you, otherwise, the code gets a bit more complex and involved....

Merge a cell in excel, depending on it's value

I want to merge a cell automatically with the one underneath if the cell has a certain value ("vv").
a solution i found is to check every cell in an array every time a change is made, but thought there would be a possibility to check the value of a cell after it changed?
So if I enter in a blank cell "vv" (without quotes) and I select a different cell I'd like that cell (with vv in it) to merge with the one right under it.
in my solution with the array it takes a second every time you change a cell, which is not neat if you make a lot of changes.
Any help?
Try this code in your worksheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Value = "vv" Then Target.Resize(2).Merge
End Sub
In case you want to prevent any content in the cell below, this code will ask you if the cells shall be merged in case any content is found:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Value = "vv" Then
If Target.Offset(1).Value "" Then
If MsgBox("Do you want to overwrite the cell below (containing '" & _
Target.Offset(1) & "?", vbYesNo) = vbYes Then
Target.Resize(2).Merge
End If
Else
Target.Resize(2).Merge
End If
End If
End Sub
Note: The code needs to go in the target sheet, not a new module, as it is an Event procedure: