Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application.OnKey Procedure error - Cannot run Macro

Tags:

excel

vba

I am working on a module which uses an onkey event to detect if backspace or delete is pressed, if it meets the criteria for the event, the corresponding cells will clear contents.

I have a procedure to launch the corresponding sub, but I get an error 'the macro cannot be found'

I have attached an image of the error and the code below, any suggestions?

Image of error enter image description here

Code

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If ActiveCell.Column = 2 Then
   Application.OnKey Key:="{DEL}", Procedure:="DeleteResources"
   Application.OnKey Key:="{BACKSPACE}", Procedure:="DeleteResources"
End If
End Sub

Public Sub DeleteResources()
ActiveCell.Offset(, 1).ClearContents
ActiveCell.Offset(, 2).ClearContents
ActiveCell.Offset(, 3).ClearContents
End If
End Sub
like image 367
PootyToot Avatar asked Oct 25 '25 05:10

PootyToot


2 Answers

You need to put DeleteResources into a code Module so that it has full public scope, particular when you use late-binding of procedure names.

Further, you need to remove the extra End If you have in that method.

like image 178
joehanna Avatar answered Oct 26 '25 18:10

joehanna


Just as an FYI, since you already have a working solution, you don't actually have to move the routine, you just need to prefix the name with the code name of its container module:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim sProc As String
    sProc = Me.CodeName & ".DeleteResources"
    If ActiveCell.Column = 2 Then
       Application.OnKey Key:="{DEL}", Procedure:=sProc
       Application.OnKey Key:="{BACKSPACE}", Procedure:=sProc
    End If
End Sub

Public Sub DeleteResources()
    ActiveCell.Offset(, 1).Resize(, 3).ClearContents
End Sub
like image 25
Rory Avatar answered Oct 26 '25 19:10

Rory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!