Excel Error on Application.OnKey Statement - excel

I put this simple code into Visual Basic:
Sub HelloWorld()
MsgBox "Hello World"
End Sub
Sub OnKeyDemo()
Application.OnKey "^+a","HelloWorld"
End Sub
When I press CTRL+SHIFT+A on the Workbook, I get the following error:
I enabled all macros on Excel and I did a Step Into procedure recommended by others on StackExchange. Neither have worked.
Thanks!

You are getting this error because the Application.OnKey is not able to find the HelloWorld subroutine.
Microsoft's documentation does not have clear information regarding where the procedure should reside, in the general module or worksheet/workbook module.
I have tried and tested by adding this procedure in the workbook/worksheet and general module. It only works in the General Module
To add a general module:
Open the Project Explorer (Ctrl+R) and right-click on any item.
Then Select Insert->Module
In the general module add the Sub HelloWorld() procedure and it will definitely work.
Very Important
Reverse the OnKey Statement as not doing this may cause unexpected results.
For Doing this follow the below steps:
Go to the ThisWorkbook Code Pane
Above the code pane you will find two dropdowns, select Workbook in first and BeforeClose in the second.
In the added code for BeforeClose, write Application.OnKey "^+a", note the lack of ,"HelloWorld".
Omitting the ,"HelloWorld" is fine since the second parameter for the Application.OnKey procedure is optional.
What Application.OnKey "^+a" does is resets the previously assigned key binding to the HelloWorld procedure.
I hope that I have been of help.

Related

Assign a keyboard shortcut to a Microsoft Excel Add-in

My friend shared a .bas file with me and told me to save it as .xlam in the vbEditor to have it as an Addin.
I've browsed in Add-ins and am able to enable it in my workbook.
Is there a way I can assign a keyboard shortcut to the Add-in? There's only one sub in that add-in file now.
I tried writing another sub with
Application.onKey "+^{C}" ,'Calculate'
But it doesn't trigger the sub to be executed.
You don't assign a shortcut to an add-in. Rather, you assign a shortcut to a macro - that is, a Public Sub procedure in your standard module.
So your code file might look like this:
Option Explicit
Public Sub Calculate()
'...code...
End Sub
Open it in Notepad. I'll look like this:
Attribute VB_Name = "Module1"
Option Explicit
Public Sub Calculate()
'...code...
End Sub
Under Public Sub Calculate(), you want to add an attribute so that the file looks like this:
Attribute VB_Name = "Module1"
Option Explicit
Public Sub Calculate()
Attribute Calculate.VB_ProcData.VB_Invoke_Func = "C\n14"
'...code...
End Sub
This is exactly how Excel's macro recorder assigns macro hotkeys: no need for any Application.OnKey work-arounds.
Save the file, import it into your VBA project: Ctrl+Shift+C will now invoke that macro.
If you're using Rubberduck, forget all of the above and just go to your module in the VBA editor, find the procedure and annotate it like so:
Option Explicit
'#ExcelHotkey("C")
Public Sub Calculate()
'...code...
End Sub
Where "C" will make the hotkey Ctrl+Shift+C; I'd warmly recommend not using "c" to avoid hijacking Ctrl+C (Copy).
Bring up the code inspections toolwindow, hit the "refresh" button; under "Rubberduck Opportunities" there should be an inspection result warning about annotations & attributes being out of sync - select "add member attribute" from the "Fix" menu, and you're done - no need to export/edit/import or deal with any obscure syntax, and if you want to change the hotkey, simply edit the comment accordingly and re-synchronize annotations & attributes.
See VB_Attribute annotations for more information.
As for saving your VBA project as an add-in, simply save your VBA project's host workbook as a .xlam add-in file, then close Excel altogether and re-open it - load your .xlam from the Developer Ribbon tab's "Excel Add-ins" button (hit "Browse" to locate your .xlam file if it's not in the list).

Workbook_Open() won't execute Excel 2011

Using Excel 2011 (should be same as Excel 2010)
Code is under the "ThisWorkbook" module in Excel
Events are enabled
Macros are enabled
I can't seem to get either Workbook_Open() or Workbook_BeforeClose() to execute. I've read numerous posts on the subject but no solution. Here is some simple test code that should execute but doesn't. Any help would be greatly appreciated.
Private Sub Workbook_Open()
ActiveSheet.Range("BL4").Value = "Open is working"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error Resume Next 'in case the menu item has already been deleted
ActiveSheet.Range("BL5").Value = "Close is working"
End Sub
First make sure you have put this in this in the right place and have macros enabled.
Then, try adding this line to the workbook_open method:
MsgBox "HELLO"
Do you see the msg box? You're choice of cell looks a bit strange
Also, I think you need to use a .xlsm file not .xlsx (Although not sure on that one)
FInally, if a plugin calls something like this line, it could cause your events not to fire..
Application.EnableEvents = False
So make sure you have tested it with no other sheets or addins open.

Excel VBA - call same macro from both Ribbon and AutoOpen

Having just upgraded to Excel 2013, I've moved my macros from a legacy custom toolbar to a custom ribbon menu. All works well, except for one thing. I used to have a macro that ran on AutoOpen, but could also be called manually via a button on the toolbar.
I call my macro from the ribbon using Sub myMacro(control As IRibbonControl) which works. But if I Call myMacro(control As IRibbonControl) in AutoOpen I get an "expected list separator" error. Conversely if I just Call myMacro() in AutoOpen I obviously get a "argument not optional" error. Bit of a Catch 22!
I know that I could just move my code to a third sub-routine, called by two separate macros in the ribbon and in AutoOpen, but before I admit defeat and do this I wonder if there is a way around this.
I have searched the web for a solution to this, but couldn't find anything that answered my particular query.
Thanks
Rob
A simple code as this will help?
Option Explicit
Sub AutoOpen()
Dim ctl As IRibbonControl
myMacro ctl
End Sub
Sub myMacro(control As IRibbonControl)
MsgBox "Hello World"
End Sub

How to run a sub in a custom "add-in" VBA when an excel file is opened? without having to write custom code in any new file?

I'm making an auto-backup for excel and I cannot find a way to run a sub procedure (that starts a timer) in my custom "add-in" code.
I've found the Workbook_Activate or Workbook_Open sub but they must be created in the worksheet and not in the "add-in" therefore everyone who would want to use the backup feature from the add-in should write that code, which is not manageable.
Is there anyway?
thanks
Oh, sorry.. after I've asked it I've found this:
Private Sub Auto_Open()
startBackupTimer
End Sub
which works!

Trap delete key

My problem is fairly trivial: I need to apply logic to the delete button in Excel. In a related question I asked for means to clear cells in a pivot table, and realising now that this might not be the right approach, this is yet another alternative I'm considering. Unfortunately, I admittedly have little experience with Visual Basic, and this task is proving such a challenge (quite surprisingly).
Is it possible to trap (as in listen to) the delete-key in Excel and trigger a subroutine in VBA when pressed?
I'd appreciate all kind of input! Thanks!
Yes.
You case use Application.Onkey to assign code to keys
If you
(1) add this code to a sheet module that contains your pivottable (right-click your sheet tab, View Code and past the code below)
This code activates and then de-activates the intercept when the user enters then leaves this particular sheet:
Private Sub Worksheet_Activate()
Application.OnKey "{DELETE}", "Intercept"
End Sub
Private Sub Worksheet_Deactivate()
Application.OnKey "{DELETE}"
End Sub
(2) add this code to a regular module
Sub Intercept()
MsgBox "user just pressed delete"
End Sub
then delete on that sheet will be trapped and the user given a message

Resources