Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA: How to trigger an Event from code?

Tags:

excel

vba

I have a Worksheet_BeforeDoubleClick event that opens a listbox in the target cell. I was asked to provide the same functionality via a button instead of (or in addition to) the double-click.

In the button's Click event I entered:

Call Worksheet_BeforeDoubleClick(Selection,true)

...so the button simply "doubleclicks" the cell. It seems to work well, but before I start using this technique throughout my project, I'd like to know if there are pitfalls I should be aware of.

What are the best practices when calling an event, either from another event or from a standard code module?

like image 788
Shawn V. Wilson Avatar asked Nov 28 '13 19:11

Shawn V. Wilson


People also ask

How do you trigger VBA macros to run based on a specific cell value change?

Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code. In the window that opens, select Worksheet from the left drop-down menu and Change from the right drop-down menu.


1 Answers

I'd like to know if there are pitfalls I should be aware of.

Yes there is one major pitfall. The Selection necessarily might not be a range. See this example

  1. Insert a button

  2. Insert a blank chart

  3. Insert an image in the chart. Let the image be highlighted

enter image description here

Let's say we have this code

Private Sub CommandButton1_Click()
    Call Worksheet_BeforeDoubleClick(Selection, True)
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    MsgBox Target.Address
End Sub

Now press the button and you will get an error.

enter image description here

The worksheet events WILL fire when they NEED too... They won't when the selection is not appropriate.

Having said that you CAN make your command button code work like this

Private Sub CommandButton1_Click()
    '~~> Check if what the user selected is a valid range
    If TypeName(Selection) = "Range" Then
        Call Worksheet_BeforeDoubleClick(Selection, True)
    Else
        MsgBox "Not a Valid Range"
    End If
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    MsgBox Target.Address
End Sub

But then where all and what all CHECKS will you place :) The best way is to place it in a Sub as @Sam suggested and then call it either from Button/Worksheet_BeforeDoubleClick.

If you still want to call it from a button then ensure that all relevant checks are in place including a proper error handler.

like image 56
Siddharth Rout Avatar answered Oct 18 '22 18:10

Siddharth Rout