I read a lot of pages saying that, but none of them put the solution if the value change by an "if function" not by hand.
The code I get is that:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Me.Range("A18:A30")) Is Nothing Then Exit Sub
Application.EnableEvents = False 'to prevent endless loop
On Error GoTo Finalize 'to re-enable the events
MsgBox "You changed THE CELL!"
Finalize:
Application.EnableEvents = True
End Sub
It only works if I change the value by hand.
Thank you in advance.
Another solution; instead of triggering your function every time when your worksheet recalculates, add a function in a module:
Function DetectChange() As Integer
MsgBox "You changed THE CELL!"
DetectChange = 0
End Function
Assuming the outcome of your formula is numeric:(otherwise outcome of function must be a empty string and the "+" must be "&")
Add to your IF-formula at the end ...+Detectchange()
Now there will be a msgbox only when your formula is recalculated
Edit by Darren Bartrup-Cook:
I found this code gave worked when the formula recalculated. It didn't fire if I changed a cell that doesn't affect the cell it's entered to and it didn't fire using Calculate Now or Calculate Sheet.
It did occasionally fire for all formula that I used the function in, but that seemed to be when I was debugging - maybe further investigation needed.
Public Function DetectChange()
MsgBox "You changed cell " & Application.Caller.Address
End Function
e.g.:
=IF(A1=1,A2,A3) & DetectChange() entered in cell A4 displays the message "You changed cell $A$4" if cells A1, A2 or A3 is changed.
Write this in Sheet1 and run the TestMe sub:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Me.Range("A1:A30")) Is Nothing Then Exit Sub
Application.EnableEvents = False
On Error GoTo Finalize
MsgBox "You changed THE CELL!"
Finalize:
Application.EnableEvents = True
End Sub
Sub TestMe()
Range("A1") = 34
End Sub
It has worked quite ok on my PC.
If the cell is changed by a built-in Excel function, then the comment of #Vincent G states the correct answer:
Worksheet_Change event occurs when cells on the worksheet are changed by the user or by an external link. and This event does not occur when cells change during a recalculation. Use the Calculate event to trap a sheet recalculation.
If you want to track the calclulation event based on some changes at Range(A18:A30) this is a working solution:
Add a new Worksheet to your Workbook (Sheet2);
In the current Worksheet write the Calculate event:
Private Sub Worksheet_Calculate()
Dim cell As Range
For Each cell In Sheet2.Range("A18:A30")
If cell <> Sheet1.Range(cell.Address) Then
cell = Sheet1.Range(cell.Address)
End If
Next cell
End Sub
In the Sheet2 write an event, catching the changes.
As simple as #Vincent G says.
Private Sub Worksheet_Calculate()
Call YourFunction
End Sub
I want to clear the selection on sheet "sheet2" when leaving the sheet. (e.g reset to cell A1)
I tried:
Private Sub Worksheet_Deactivate()
ActiveSheet.Range("A1").Select
End Sub
And:
Private Sub Worksheet_Deactivate()
Sheets("Sheet2").Range("A1").Select
End Sub
But this is not working. (first one selects A1 on the current sheet, and the second one gives an error)
The reason why I want this, is because a macro has selected an object (Shape form control) that is protected (locked text). When a user leaves and returns to the sheet, while this object is still selected an error occurs:
You cannot use this command on a protected sheet. To use this command... etc
The reason why a macro selected the object in the first place, is because the user clicked on a hyperlink that would highlight this object. (I can't think of a different way then 'select' to highlight a shape form control)
Possible solution:
The only other method I can think of is have a Sub "Worksheet_Deactivate()" that first activates sheet "Sheet2" clears the selection to A1 and then returns to the sheet the user has initially clicked on when leaving the sheet..... but this feels cumbersome.
Is there another solution/method? any help is appreciated!
This will work so long as you are not working in a shared workbook:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Sheet2" Then Sh.Protect
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
If Sh.Name = "Sheet2" Then Sh.Unprotect
End Sub
Cheers!
Based on this answer, you can use the Workbook_SheetDeactivate event and get a WorkSheet object that you can then change the selection on without switching the active sheet.
Further reading seems to indicate Me will contain the sheet that has just been deactivated in the Worksheet_Deactivate handler, so you could also use that.
I have a worksheet with a clickable shape and a class listening to the change events of that sheet:
Sheet1:
Public Sub Shape_click()
Debug.Print "click"
End Sub
Class1:
Private WithEvents sh As Worksheet
Private Sub Class_Initialize()
Set sh = Sheet1
End Sub
Private Sub sh_Change(ByVal Target As Range)
Debug.Print "change: " & Target.Address
End Sub
When I edit a cell in Sheet1 and click directly on the shape the output is
click
change: $B$1
I would like to trigger the change event in the shape macro so that the change event would occur before printing "click". DoEvents, Sleep from kernel32 and activation of some other cell from the Shape_click were not working for me.
I have found two "hacks", the first one quite limited, but the second one does the job:
Selection.Cut:
Public Sub Shape_click()
Selection.Cut Selection
Debug.Print "click"
End Sub
It makes the Change event to fire 3 times (2x before "click", 1x after that), every time with the right (changed) value.
Of course you need to check the Selection (if it is set, if it's of Range type etc.)
The solution is quite limited as you can't use it with merged cells in the selection (will ask if you want to unmerge them).
Selection.Value = Selection.Value
Public Sub Shape_click()
Selection.Value = Selection.Value
Debug.Print "click"
End Sub
Works even with merged cells. There is also need to check Selection if it really contains a range.
I am working with Excel VBA and I have a macro that is fired everytime a specific cell is changed. That macro affects the value and properties of many cells on the worksheet, so I used
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
[...] 'mycode
Application.EnableEvents = True
End Sub
At the beginning and end of the macro. Otherwise whenever I change the cell that fires the macro, the macro changes cell and thus fires itself over and over again.
I would like for the macro to be fired if I manually change a cell (without having to insert a command button that fires the macro or something similar)
Is that possible?
Thanks for the help
Private Sub Worksheet_Change(ByVal Target As Range)
If (Target.Column =4) Then
MsgBox ("mycell changed")
End If
End Sub
This basically says if the column change occurs in Index 4 (D) then msgbox.
if you didn't have the if statement the messgbox would occur anytime a change occurs to any cell in the worksheet.
Protecting workbook structure will prevent a user from deleting sheets. But how could I (using VBA) prevent a user from deleting a particular sheet I designate? I've seen examples where an active sheet is prevented from deletion by
Set mymenubar = CommandBars.ActiveMenuBar
mymenubar.Controls("Edit").Controls("Delete sheet").Visible = False
in its Worksheet_Activate event but that of course only works if the sheet is activated.
Is there a way to prevent a sheet from being deleted whether active or no?
For clarity: I'm fine with the user deleting some sheets, just not a couple of particular sheets.
So protecting workbook structure won't work.
As far as I can tell, it isn't possible to natively tag a single sheet as non-deletable; and there isn't an event that can be used to detect when a sheet is about to be deleted so the workbook can be protected preventively.
However, here is one potential workaround:
Protect workbook structure: this will, as you indicate, prevent all sheets from being deleted.
Create a "Controls" sheet. On this sheet, maintain a list of all sheet names (except those you don't want to be deletable).
If users want to delete a sheet, they will have to select its name on the Controls sheet (e.g. in a data validation drop-down menu) and press a "Delete" button. This button will call a macro that temporarily unprotects the workbook, deletes the selected sheet, and then reprotects the workbook.
Of course, the users will have to get used to this way of deleting sheets (as opposed to just right-click > Delete on the sheet's tab). Still, this isn't crazy complicated.
As for how to achieve #2 i.e. maintaining that list of sheet names, I suppose you could make use of a UDF like this one (must be called as an array formula):
Function DeletableSheetNames() As String()
Application.Volatile
Dim i As Long
Dim sn() As String
With ThisWorkbook
ReDim sn(1 To .Sheets.Count)
For i = 1 To .Sheets.Count
With .Sheets(i)
If .Name = "DataEntry1" Or .Name = "DataEntry2" Then
'Don't include it in the list.
Else
sn(i) = .Name
End If
End With
Next i
End With
DeletableSheetNames = sn
End Function
You cannot stop users to delete a particular sheet but you could use the Workbook_BeforeSave() event to prevent the workbook from being saved if a particular sheet is missing. The documentation on this event precisely shows how to allow saving a workbook only when certain conditions are met. See http://msdn.microsoft.com/en-us/library/office/ff840057(v=office.14).aspx
I can prevent a sheet from being deleted via the Worksheet_BeforeDelete Event as follows:
Private Sub Worksheet_BeforeDelete()
Call ThisWorkbook.Protect("password")
Call MsgBox("This sheet cannot be deleted.", vbExclamation)
End Sub
This protects all sheets from being deleted, however if you add some event code on the ThisWorkbook module like the following :
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Call ThisWorkbook.Unprotect("password")
End Sub
I will then be able to delete any other sheet as soon as it is selected.
Bear in mind, you will lose copy and paste functionality between pages due to the page unlocking when it is selected.
"there isn't an event that can be used to detect when a sheet is about to be deleted"
Since Office 2013, it is possible with the SheetBeforeDelete event.
I found this solution, similar to Dan's, on ExtendOffice.com. Put this code on the Worksheet's module:
Private Sub Worksheet_Activate()
ThisWorkbook.Protect "yourpassword"
End Sub
Private Sub Worksheet_Deactivate()
ThisWorkbook.Unprotect "yourpassword"
End Sub
When you activate the sheet in question, the whole workbook is protected, and the "Delete" option is grayed out. When you switch to any other sheet, the workbook is free again. It's subtle because you only notice the change when you go to the "safe" sheet.
Answer is by adding the following code to each of the protected sheets:
Private Sub Worksheet_Deactivate()
ThisWorkbook.Protect , True
Application.OnTime Now, "UnprotectBook"
End Sub
And the following to a Module:
Sub UnprotectBook()
ThisWorkbook.Unprotect
End Sub
Check https://www.top-password.com/blog/prevent-excel-sheet-from-being-deleted/ for credits accordingly.
The following disables the menu when you right click on tab. This stops the delete option being available.
Sub tab_rclick_off()
Application.CommandBars("Ply").Enabled = False
End Sub
The following turns the menu back on.
Sub tab_rclick_on()
Application.CommandBars("Ply").Enabled = True
End Sub
This option is simple, concise, prevents any issues with data entry/editing with protected sheets and can be called from anywhere in code, ie in conjunction with log on permissions can be given to some and not others etc. foremost yourself.
Maybe you could try to protect the structure of the workbook in SheetBeforeDelete.
See my example:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
ThisWorkbook.Protect Structure:=False
End Sub
Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
If Sh.Name = "Example" Then
ThisWorkbook.Protect Structure:=True
End If
End Sub
Here is another answer from mine base on the idea of #Jean-François Corbett
You can use 'Protect WB Structure' and Event 'Workbook_SheetBeforeDelete' to achieve this.
The result is that an dialog will pop up said "Workbook is protected and cannot be changed."
Private Sub zPreventWShDel(WSh As Worksheet, Protection As Boolean)
Dim zPassword As String: zPassword = ""
Dim zWB As Workbook
Set zWB = WSh.Parent
If Protection Then
zWB.Protect zPassword, Protection
Else
zWB.Protect zPassword, Protection
End If
'Stop
End Sub
Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
Call zPreventWShDel(Sh, True)
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Call zPreventWShDel(Sh, False)
End Sub
Do not Call the code on Sheet Deactivation like below. Because it will deactivate it. Sequence of running is Event_SheetBeforeDelete -> Event_SheetDeactivate.
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Call zPreventWShDel(Sh, False)
End Sub
I created a different approach to this.
On the sheet(s) you want protected, add this code:
Private Sub Worksheet_BeforeDelete()
ThisWorkbook.Worksheets("Unprotect Workbook").Visible = True
ThisWorkbook.Worksheets("Unprotect Workbook").Activate
ThisWorkbook.Protect
End Sub
Create the ("Unprotect Workbook") sheet and make the visibility: xlSheetVeryHidden
on the "Unprotect Workbook" sheet add a button or shape that you can assign a macro to.
on the "Unprotect Workbook" sheet, add this code:
Sub unprotectThisWorkbook()
ThisWorkbook.unprotect
ActiveSheet.Visible = xlSheetVeryHidden
End Sub
Assign the sub you added, "Sub unprotectThisWorkbook()", to the button on the "Unprotect Worksheet" sheet
When you delete the sheet you protected, the workbook is protected and it takes you to the unprotect worksheet as a notice to the user and as a way to unprotect the workbook. Once the button is clicked, the workbook is unprotected and the "unprotect sheet" is hidden again.
This will work for any sheet you want to protect.