• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Using a loop to assign subs to all 12 function keys

Jeff999

New Member
Hi,

I can manually assign a different sub to each of the 12 function keys using separate Application.OnKey statements in Auto_Open. However the subs are very similar to one another, so it would be better to have a single sub that would know which function key activated it. One way to do this is to again have 12 Application.OnKey statements that would pass the key number to the single sub as a parameter. I was wondering if the 12 statements can be reduced further with a For...Next loop. But I can't get it to work. Perhaps something like this will work, if someone can help me with the syntax, or perhaps I'm on the wrong track altogether.

Code:
Sub Auto_Open
For x=1 to 12
Application.Onkey "{F" & cstr(x) & "}", "'TestMacro  x'"
Next x
End Sub

Sub TestMacro(ByVal y as Integer)
MsgBox "The sub was activated by function key " & y
End Sub
 
Last edited by a moderator:
You were very close:

Code:
Sub Auto_Open()
    For x = 1 To 12
        Application.OnKey "{F" & CStr(x) & "}", "'TestMacro  " & x & "'"
    Next x
End Sub
 
Back
Top