PDA

View Full Version : Assign Shortcut key via Userform (Application.KeyBindings.Add)



ACFeddes
10-29-2011, 06:57 AM
Hello,
I’m trying to assing a shortcut key to a macro using VBA. I’ve created a Userform with 3 checkboxen and a Textbox.
Application.KeyBindings.Add .... Works is I manually enter the correct keys using wdKey input, but it doesn’t work if generate this string with my form.
Has anybody got an idea how I can make this work?

Regards,
ACF

Underneath my code (+ comments)


Private Sub OK_Click()
'I've created a userform with three checkboxes (for Ctrl / Shift / Alt) and a TextBox1 (for character)
'Then try to get the below code to assign a shortcut key to a macro.
'But it doesn't recognise the string I generate????

Dim FC, Ctrl, Shift, Alt, Choice
Application.CustomizationContext = NormalTemplate

Choice = "wdKey" & TextBox1
FC = "wdKeyControl, wdKeyShift, wdKeyAlt, " & Choice

If CB_Ctrl = True And CB_Shift = True And CB_Alt = True Then
MsgBox FC '"wdKeyControl, wdKeyShift, " & Choice
'This gives back the string I would normally place between brackets behind the 'BuildKeyCode' but the code _
below does not accept this, stating: 'types don't match

'Application.KeyBindings.Add KeyCode:=BuildKeyCode(FC), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="Assign_SK_Test_Msg"
Else
MsgBox "Not all three checkboxes ticked"
End If

Unload Me

End Sub

Paul_Hossler
10-29-2011, 10:42 AM
I don't think you're using BuildKeyCode correctly

You're passing it a string that only sort of looks like the arguments

If you want to assign Ctrl+Shift+Alt+some letter, I think you'll need to do it like this, passing 1, 2, 3, or 4 wdKey values


KeyCode:=BuildKeyCode(wdKeyControl, wdKeyShift, wdKeyAlt, TextBox1.Value), _


Paul

ACFeddes
10-29-2011, 11:36 AM
Hello Paul,
Thanks for your reply, but that doesn’t help.

I’ll attach the form + code.

If I use the code below it will work:
VBA
Application.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeyShift, wdKeyAlt, wdKeyI), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="Assign_SK_Test_Msg"

But if I use, it will not work, though the MsgBox FC returns the same value as between above brackets, i.e. (wdKeyControl, wdKeyShift, wdKeyAlt, wdKeyI):
VBA
Application.KeyBindings.Add KeyCode:=BuildKeyCode(FC), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="Assign_SK_Test_Msg"

Perhaps you can try the form and see if you can take it any further.

Thanks for your reply anyway,
Alex