Warm tip: This article is reproduced from serverfault.com, please click

Issues with Application.Onkey

发布于 2020-11-28 08:17:31

I've looked at about every article/question on this issue that I've been able to find, but no luck -- thanks in advance for your help:

In my "This Workbook," I have the following:

Option Explicit

Public Sub Workbook_Open()
Application.OnKey "+^%{+}", "Insert_Columns"
End Sub

In a Module, I have the following:

Sub Insert_Columns()

Dim num As String

num = InputBox("How many columns do you want to insert?")

If num <> "" Then
    If num > 0 Then ActiveCell.Offset(0, 1).Resize(1, num).EntireColumn.Insert
End If

End Sub

For some reason, the shortcut is not working. I've tried many variations of this, but does anyone have an idea why the shortcut would not be working? The macro runs great if I click "Run" manually.

Thank you!

Questioner
jg43
Viewed
0
Super Symmetry 2020-11-29 03:03:12

First of all you don't need the first +, you can simply have "^%{+}".

Second, to access the + character you need to press the Shift key (in most standard keyboards, + is on the = button), what this means is that you need to press Ctrl+Alt+Shift+= to run the procedure. If you don't want to press the Shift key, then use "^%{=}"

Aside:

You may want to place these OnKey settings in Workbook_Activate and reset them in Workbook_Deactivate. This avoid running these procedures when the workbook is closed or it is not the active one. Please note how I fully qualified the procedure name to avoid a conflict with another procedure that may have the same name in a different open workbook.

Private Sub Workbook_Activate()
  '* Set OnKey shortcuts
  Application.OnKey Key:="^%{=}", Procedure:=ThisWorkbook.Name & "!Insert_Columns"
End Sub

Private Sub Workbook_Deactivate()
  '* Reset OnKey shortcuts
  Application.OnKey Key:="^%{=}", Procedure:=""
End Sub

A final thing to consider is using Application.InputBox rather than InputBox as the former gives you more control over what the user enters. Find docs here.

Sub Insert_Columns()

  Dim num As String
  
  '* Type:=1 -> Number
  num = Application.InputBox("How many columns do you want to insert?", Type:=1)
  
  '* Application.InputBox returns False if x or Cancel buttons are pressed
  If num Then
      If num > 0 Then ActiveCell.Offset(0, 1).Resize(1, num).EntireColumn.Insert
  End If

End Sub