I'm using a Worksheet_Change to ClearContents on specific cells. The cell being evaluated for the change is "A10". This value comes from a data validation list. I've noticed that when there is a value in this cell and I click the dropdown, even if I re-select the same value from this list, the clear contents performs. Is there a way to avoid this? I'm worried that the users of this sheet will want to view the options in the dropdown, but will ultimately keep the original A10 value and still lose the contents of the other cells.
Here is the code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rang As Range
Set rang = Worksheets("Sheet1").Range("A10")
If Not Intersect(Target, rang) Is Nothing Then
Worksheets("Sheet1").Range("B10:B50000", "C10:C50000").ClearContents
End If
End Sub
Thanks in advance!
Here is a version of your macro that keeps track of the old value in A10
If no real change is made, it just goes away:
Dim OldValue As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rang As Range
Set rang = Worksheets("Sheet1").Range("A10")
If IsEmpty(OldValue) Then
OldValue = rang.Value
Exit Sub
End If
If Not Intersect(Target, rang) Is Nothing Then
If OldValue = rang.Value Then
Exit Sub
End If
OldValue = rang.Value
Application.EnableEvents = False
Worksheets("Sheet1").Range("B10:B50000", "C10:C50000").ClearContents
Application.EnableEvents = True
End If
End Sub
Because OldValue is DIM'ed above the sub, its value is preserved from call to call.
Related
I am trying to create a code using vba whereby I want to make a certain cell B2 read-only and unchangeable when session is unlocked (I have a lock and unlock module for later whereby locked disallow editing and unlocked allows editing).
The code aims to give an error message and restore the cell to the previous value before edits are made when session is locked.
Problem: However, currently the results from this code successfully gave an error message when edit is done when locked BUT made the cell blank after the error message when I actually want it to restore to the previous value before edit was made
Please help if you know what went wrong and thank you in advance
Public locked As Boolean
Dim oldValue As Variant
Private Sub worksheet_SelectionChange(ByVal Target As Range)
oldValue = Target.Value
End Sub
Private Sub worksheet_Change(ByVal Target As Range)
If Target.Row = 2 And Target.Column = 2 Then
If locked Then
If Target.Value <> oldValue Then
Target.Value = oldValue
MsgBox "You are not allowed to edit!"
End If
End If
End If
End Sub
An Events Duo: Change and SelectionChange
In the Worksheet_SelectionChange event you can safely use Target because you can select only one cell at a time.
In the Worksheet_Change event you could have copied hundreds of cells which are the cells Target is referring to. But you are only interested in one cell, so use intersect and use a variable to get this single cell and do the operations necessary on it. Also, to avoid an endless loop by constantly retriggering the event, disable events before writing to the worksheet but don't forget to enable them immediately after writing.
Option Explicit
' If you're using the variables outside of this module, they need
' to be declared as 'Public'. Otherwise, use 'Private' ('Dim' is the same
' but it's kind of reserved for inside procedures).
Public Locked As Boolean
Private Const CellAddress As String = "B2"
Private OldValue As Variant
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Range(CellAddress), Target) Is Nothing Then
OldValue = Target.Value
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim iCell As Range: Set iCell = Intersect(Range(CellAddress), Target)
If Not iCell Is Nothing Then
If Locked Then
If StrComp(CStr(iCell.Value), CStr(OldValue), vbTextCompare) _
<> 0 Then
Application.EnableEvents = False ' prevent retriggering
iCell.Value = OldValue
Application.EnableEvents = True
MsgBox "You are not allowed to edit!"
End If
End If
End If
End Sub
I have 4 Cells (S11:T12) and a Command Button 1, what I want is, until all 4 cells are populated the command button should be disabled (Which I can do from the properties tab) and once all 4 cells are filled with number, the command button should be enabled and once the data from these cells are deleted, the command button should be disabled again.
Under which event should I write the code?
I tried this, but it does not work.
Private Sub Workbook_Open(Cancel As Boolean)
If Sheets("WorkArea").Range("S11:T12") = "" Then
Sheets("WorkArea").CommandButton1.Enabled = False
Else
Sheets("WorkArea").CommandButton1.Enabled = True
End If
End Sub
Use the WorkSheet_Change event handler to handle the change in cells, and you can use the CountBlank worksheet function to determine if a range is empty.
Private Sub Worksheet_Change(ByVal Target As Range)
If WorksheetFunction.CountBlank(Range("S11:T12")) = 4 Then
Sheets("WorkArea").CommandButton1.Enabled = False
Else
Sheets("WorkArea").CommandButton1.Enabled = True
End If
End Sub
Worksheet_Change
CountBlank
According to your question however, you actually want:
Private Sub Worksheet_Change(ByVal Target As Range)
If WorksheetFunction.CountBlank(Range("S11:T12")) = 0 Then
Sheets("WorkArea").CommandButton1.Enabled = True
Else
Sheets("WorkArea").CommandButton1.Enabled = False
End If
End Sub
A Worksheet Change
This solution will not work if the critical range contains formulas.
To count the number of cells that are not empty you can use the WorksheetFunction.CountA method.
Usually you don't want this code to run when there are changes outside of the range, so you will restrict the code to the range with the Application.Intersect method. You don't have to enable or disable the command button on each change since obviously the code will run on each change.
Since this is all happening in worksheet "WorkArea", there is no need to refer to it by its name i.e. you can safely use Range(rngAddress) and CommandButton1 instead of ThisWorkbook.Worksheets("WorkArea").Range(rngAddress) and ThisWorkbook.Worksheets("WorkArea").CommandButton1 respectively.
The Code
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const rngAddress As String = "S11:T12"
Dim rng As Range
Set rng = Range(rngAddress)
If Not Intersect(Target, rng) Is Nothing Then
If WorksheetFunction.CountA(rng) = rng.Cells.Count Then
CommandButton1.Enabled = True
Else
CommandButton1.Enabled = False
End If
End If
End Sub
I am using worksheet change event to trigger copy paste values. Worksheet change code is in the sheet2
Sub worksheet_change(ByVal Target As Range)
Application.EnableEvents = True
Set Target = Range("AB2")
If Target.Value = "OK" Then
Call myTR1
End If
Please note AB2 cell takes it's value from another sheet
Copy paste code is in a Module
Sub myTR1()
Sheets("BA1").Range("AR6:AS8").Value = Sheets("BA1").Range("AL17:AM19").Value
End Sub
When target range changes to "OK", my copy paste macro is not triggering. What am I doing wrong?
Using your eaxct code worked, although you didnt have end sub in your example?
EDIT:
Bear in mind the 'OK' is case sensitive so it will have to be in uppercase to fire, if you want it to fire either on lower or upper you can use the second code.
Sub worksheet_change(ByVal Target As Range)
Application.EnableEvents = True
Set Target = Range("AB2")
If Target.Value = "OK" Then
Call myTR1
End If
End Sub
Sub worksheet_change(ByVal Target As Range)
Application.EnableEvents = True
Set Target = Range("AB2")
If Target.Value = "OK" Or Target.Value = "ok" Then
Call myTR1
End If
End Sub
I want a msgbox to show up only once when formula result changes in my table range ("K2:K5"). Right now it shows twice.
In this range I have excel-formulas. Formula: H12*10
These formulas is refering to a dropdown-list (a list that I've created from "data validation" on the excel menu Data-tab).
The dropdown-list is located in cell H12.
The values in the dropdown is refering to range(D15:D17)
I've noticed though that the msgbox shows up once when I remove the dropdown and manualy type in values in H12.
Thankful for any help on this
Private Sub Worksheet_Calculate()
Dim Xrg As Range
Set Xrg = Range("K2:K5")
If Not Intersect(Xrg, Range("K2:K5")) Is Nothing Then
MsgBox "Hi"
End If
End Sub
I have also tried to add Application.enableEvents to the code but no success.
Private Sub Worksheet_Calculate()
Dim Xrg As Range
Set Xrg = Range("K2:K5")
Application.EnableEvents = False
If Not Intersect(Xrg, Range("K2:K5")) Is Nothing Then
MsgBox "Hi"
End If
Application.EnableEvents = True
End Sub
Your current code has no added value on a Worksheet_Calculate event due to comparing two exact same ranges and see if they intersect. That would always be the case. Your code would have the same effect as:
Private Sub Worksheet_Calculate()
MsgBox "Hi"
End Sub
Might you have more functions in your worksheet that could trigger this event unwanted outside range K2:K5, you should look into the Worksheet_Change event and return a messagebox when your referenced cell has changed value.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$H$12" Then MsgBox "Hi"
End Sub
Choose either one, but don't use both cause you'll end up with two msgbox's
I am trying to hide a commandbutton based on a specific cell value. I have looked up several codes and pasted them in excel (in the vba form when right clicking the sheet and selecting "view code").
What am I doing wrong?
Here's one of the codes I've tried:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("A1") = 0 Then ActiveSheet.CommandButton1.Visible = False
If Range("A1") = 1 Then ActiveSheet.CommandButton1.Visible = True
End Sub
Make sure you enable events before using your code. Also, you must place your code in Worksheet module, not in regular module. To enable events, use this simple sub.
Sub Enable_events()
Application.EnableEvents = True
End Sub
please run this first:
Sub enable_()
Application.EnableEvents = True
End Sub
and then your Code will run perfectly:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("A1") = 0 Then ActiveSheet.CommandButton1.Visible = False
If Range("A1") = 1 Then ActiveSheet.CommandButton1.Visible = True
End Sub
Your code is confusing, for a number of reasons.
Range, when it's not qualified with a Worksheet object, implicitly refers to the ActiveSheet, i.e. ActiveSheet.Range... but when it's in a worksheet's code-behind, it implicitly refers to that worksheet's Range property, i.e. Me.Range. Because the meaning of an unqualified Range call depends on context, it's best to always qualify it with an explicit Worksheet object.
So if you're in the code-behind module for Sheet1, then Range("A1") is equivalent to Sheet1.Range("A1"), or even better, Me.Range("A1").
The two conditions will be evaluated every time, but only one of them needs to be: it's inefficient.
Truth is, you don't need to assign a Boolean literal - a Boolean expression is much cleaner.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Me.CommandButton1.Visible = (Me.Range("A1") = 1)
End Sub
Now, assuming Application.EnableEvents returns True, that code will run every time the selection changes, which is rather overkill.
Handle the Worksheet.Change event instead, and only act when the modified cell is A1:
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.Intersect(Target, Me.Range("A1")) Is Nothing And Target.Count <> 1 Then
' we don't care about that cell: bail out
Exit Sub
End If
Me.CommandButton1.Visible = (Me.Range("A1") = 1)
End Sub
Please try this code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1")) Is Nothing Then
If Selection.Cells.Count = 1 Then
If Range("A1") = 0 Then ActiveSheet.CommandButton1.Visible = False
If Range("A1") = 1 Then ActiveSheet.CommandButton1.Visible = True
End If
End If
End Sub
Hope this help.