Nickolay
Nickolay

Reputation: 32063

Run-time error 1004: Method OnKey of object _Application failed

I'm getting reports of VBA "Run-time error '1004': Method 'OnKey' of object '_Application' failed" at least on Excel 2016 under Windows in this code:

Private Sub Workbook_Deactivate()
    Application.OnKey "^x"
End Sub

(The code overrides certain hotkeys when my VBA-enabled workbook is active, and restores the default behavior when the user switches back to another workbook.)

What could be the reason?

Upvotes: 1

Views: 2985

Answers (1)

Nickolay
Nickolay

Reputation: 32063

Unexpectedly, many API calls fail when the active workbook is in the Protected view mode. I wasn't even able to switch the active workbook to ThisWorkbook via Activate.

The workaround I came up with is to dismiss "Protected view" when the user switches to such a document from my app/workbook:

If Not (Application.ActiveProtectedViewWindow Is Nothing) Then
    Application.ActiveProtectedViewWindow.Edit
End If
Application.OnKey "^x"

This gives up some of its protection, but as my users are working mainly with internal documents, this tradeoff makes sense.

Upvotes: 2

Related Questions