Need your help on modifying the code or code that will help me do complete my task.
Its a protected workbook with VBA. I have a drop down on sheet1 in B18,D20,K11 and M46 and list of values in each drop down's.
When user changes the values in drop-down B18 and D20, I want to throw a prompt with "ok" and "cancel". User selects "ok" it should run a Module 1 ( which renames sheet).
Two things I am failing to achieve.
1. I don't want to throw prompt if user changes any other drop down values apart from 2 cells mentioned above,.
2. When clicked "OK" it should run module 1.
Please suggest if you have better code
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rNg As Range
Set rNg = Range("B18", "D20")
MsgBox "Please click Calculate Button", vbOKOnly, "Calculate button"
End Sub
Try the code below.
(don't understand why you want to check if the user pressed "OK" since you are using a MsgBox with vbOKOnly and he has no other option)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rNg As Range
Dim IntersectRange As Range
Dim message As Integer
' modify here to the Range you need monitored
Set rNg = Range("B18", "D20")
Set IntersectRange = Intersect(Target, rNg)
If Not IntersectRange Is Nothing Then
message = MsgBox("Please click Calculate Button", vbOKOnly, "Calculate button")
If message = vbOK Then
Call Module1 ' or your Module / Function name
End If
Else
'Do Nothing if outside range
End If
End Sub
I am not saying this is the wright method, but you could use a UserForm to create custom prompts. And this is the way i do it, because for me it gives a better control on what i need to do.
Suppose if you create a userform with ok and cancel button, then you trigger the userform on the dropdown value change,
Sub DropDown1_Change()
UserForm1.Show
End Sub
Then write the codes for ok and cancel button clicks
Private Sub Ok_Click()
UserForm1.Hide
MsgBox "clicked ok"
End Sub
Private Sub cancel_Click()
UserForm1.Hide
MsgBox "clicked cancel"
End Sub
Related
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 have an Excel sheet that has a doubleclick event in cell "P1" (runs a macro).
I may have cell "J30" (or any other cell) selected before I doubleclick "P1"
How can I remember, and return to the cell "J30" after the "P1" doubleclick?
Storing the active cell doesn't work because the first click in the doubleclick sequence, selects "P1".
I also tried rightclick on "P1", but it also selects "P1" before running the event.
Well, it's a bit more complicated than the "duplicate thread" because the SelectionChange event is invoked prior to the BeforeDoubleClick event, so the former will update the last selection to the new one before the latter gets hand.
What you need is to go "one step further" in saving the selections, by actually saving both:
The current selection
The previous selection
Something like this should work
' Code module of your worksheet
Option Explicit
Private lastSelection As Range, beforeLastSelection As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
' Your Code for this event, i.e.
If Target.Address = "$P$1" Then
' Some code ...
Cancel = True
If Not beforeLastSelection Is Nothing Then beforeLastSelection.Select
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set beforeLastSelection = lastSelection
Set lastSelection = Target
End Sub
Using the method here you can do as follows
Public PreviousActiveCell As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox ("Previous selection: " & PreviousActiveCell.Value & vbNewLine & _
"Double clicked selection: " & Target.Value)
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static pPrevious As Range
Set PreviousActiveCell = pPrevious
Set pPrevious = ActiveCell
End Sub
Its a protected worksheet/workbook and I have a code that will throw a prompt for the user, whether to edit the sheet or not. Cells are editable, but the problem is cells are not getting highlighted with border. So its difficult for the user to know which cells is he working on.
I have 2 sheets here, Corefiller and Ad-filler, if dropdown on corefiller sheet is "No". User gets a prompt when he selects the sheet, he clicks ok to edit the sheet or cancel if he doesnt want to edit.
Code on Sheet "Ad-filler"
Option Explicit
Private mMessageDisplayed As Boolean
Private Sub Worksheet_Activate()
Carry
End Sub
Code on a module.
Public Sub Carry()
If ActiveSheet.ProtectContents And Not mMessageDisplayed Then
mMessageDisplayed = True
If ThisWorkbook.Sheets("Corefiller").Range("E29") = "NO" Then
If MsgBox("Click OK to include Filler for this request", vbOKCancel + vbInformation) = vbOK Then
ThisWorkbook.Worksheets("Corefiller").Range("E29") = "YES"
With ThisWorkbook.Sheets("Ad-filler")
.Range("E13:E14").Locked = False
End With
Else
With ThisWorkbook.Sheets("Ad-filler")
.Range("E13:E14").Locked = True
End With
End If
Else
Exit Sub
End If
End If
End Sub
Whats wrong in my code? why the cell is not highlighted. If i try to use protect/unprotect in the code, cells on the first sheet (Corefiller) will not be highlighted and I have to click on other sheets and come back to get the cell highlighted.
Can you restart, implement this and check whether the problem still exists:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Cells.Interior.ColorIndex = 0
Target.Interior.ColorIndex = 3
End Sub
Purpose: Click on a cell in a range (Range: Column K:K on excel worksheet). Once you click on a specific cell in column K, userform pops up with cell value using following code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("K:K")) Is Nothing Then
Credit_Information.TextBox1.Value = Target.Value
Credit_Information.Show
End If
End Sub
My question, is depending on where I click on column K, I want to use two buttons on my userform (Previous and Next) to move up and down column K and see the values of the cell dynamically change on my userform. Is this possible? Please let me know if any clarification is needed.
Just add the two command buttons to your userform.
Name one of the buttons cmdNext and give it a caption of "Next".
Name the other button cmdPrev and give it a caption of "Previous".
Then, in the userform code module, place these routines:
Private Sub cmdNext_Click()
ActiveCell(2).Select
End Sub
Private Sub cmdPrev_Click()
If ActiveCell.Row > 1 Then ActiveCell(0).Select
End Sub
That's it.
Note: if you want you can add code to ensure that the ActiveCell is in column K before allowing the new selections:
If ActiveCell.Column = 11 Then ...
Perfect, Thanks!
I also found out that using Offset worked for me too in this manner. I'm not sure however if I'm breaking any conventions by doing this.
Private Sub CommandButton1_Click()
ActiveCell.Offset(-1).Activate
End Sub
Private Sub CommandButton2_Click()
ActiveCell.Offset(1).Activate
End Sub
It is possible, but I would create another procedure for that. What you could do is declare a public variable in your userform & set it equal to the range Target. Then you could call another procedure from the userform on each button click and redefine the selected range after each click.
So, at the top of your userform do this:
Public selected_cell as Range
Then for the up button:
Private Sub ButtonUp.Click()
If selected_cell.Row < 2 Then Exit Sub
selected_cell.Rows(0).Select
Set selected_cell = selected_cell.Rows(0)
me.TextBox1.Value = selected_cell
End Sub
And the down button would be:
Private Sub ButtonDown.Click()
selected_cell.Rows(2).Select
Set selected_cell = selected_cell.Rows(2)
me.TextBox1.Value = selected_cell
End Sub
Now let's make your code like this:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("K:K")) Is Nothing Then
With Credit_Information
Set .selected_cell = target
.TextBox1.Value = Target.Value
.Show
End With
End If
End Sub
I would like to handle single click and double click events separately for an ActiveX button in VBA. My issue is that the single click event is called for both single and double clicks. Is there a way to supress/bypass the single click procedure when a double click event occurs? I'm sure there's a simple answer for this, but can't find anything on the web...
From Help
If there is code in the Click event, the DblClick event will never trigger, because the Click event is the first event to trigger between the two. As a result, the mouse click is intercepted by the Click event, so the DblClick event doesn't occur.
Try capturing Mouse Down and Mouse Up, wait 500 ms, if no Mouse Down, then it's a single click, if there is wait the time for a mouse down.
DoubleClickSpeed
HKCU\Control Panel\Mouse
Data type Range Default value
REG_SZ 100 - 900 (milliseconds in decimal) 500
Brad Yundt provides this clever workaround at Experts-Exchange in this post.
I have assumed you have asked this wrt Excel- pls let me know if I am mistaken
You might try using Application.OnTime to schedule a response to a
leftclick after say a 1 second delay. If a doubleclick or rightclick
occurs in the meantime, then the leftclick event in the OnTime sub
will not occur.
The following code goes in the code pane for the worksheet being watched. Note that it uses the code name for that worksheet, not the tab name.
As written, the code watches A1:A10 for either a leftclick, rightclick or doubleclick on a single cell. It then displays a message box naming the cell that was clicked and the type of click.
worksheet event code
Dim bTrapped As Boolean
Dim cel As Range, rgWatch As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(cel, Target) Is Nothing Then
MsgBox "Doubleclick at " & cel.Address
bTrapped = True
Cancel = True
End If
End Sub
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(cel, Target) Is Nothing Then
MsgBox "Rightclick at " & cel.Address
bTrapped = True
Cancel = True
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim targ As Range
Set rgWatch = Range("A1:A10")
Set targ = Intersect(Target, rgWatch)
If Not targ Is Nothing Then
If targ.Cells.Count = 1 Then
bTrapped = False
Set cel = targ.Cells(1, 1)
'Allow 1 second for user to complete a rightclick or doubleclick before trapping leftclick
Application.OnTime Now + 1 / 86400, "Sheet1.DelayedWatch" 'Note that Sheet1 is codename for worksheet (not tabname)
End If
End If
End Sub
Private Sub DelayedWatch()
If bTrapped = False Then
MsgBox "Leftclick at " & cel.Address
End If
End Sub
I know this reply is years late but to cancel an event, so as to prevent another event happening (on the same event) (ie. prevent single click for happening when you act on the double click) do the following;
Private Sub CheckBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
'Do your stuff in here to handle the doubleClick event
Cancel = True 'send back a true boolean to cancel the singleClick
End Sub