vbakingsoft

VBA. What is incorrect in this code?


Searching found code like this

Sub Workbook_Activate()
Application.OnKey "+^{RIGHT}", "YourMacroName"
End Sub

However, when I tried, I got

enter image description here

How to create procedure?

I did this

Sub YourMacroName()
   Selection.Copy
   Sheets("V").Select
End Sub

Sub Workbook_Activate()
Application.OnKey "+^{RIGHT}", "YourMacroName"
End Sub

Got the same error

What would be correct code? Or where would be tutorial for dummies? Found some examples, but they does not work

I see my tags were modified to excel and excel-vba. But I do not use excel. Use Kingsoft Office

Changed Application.OnKey "+^{RIGHT}", "YourMacroName" to .OnKey Key:="^+M", Procedure:="YourMacroName"

and got

enter image description here

Then changed to OnKey Key:="^+M", Procedure:="YourMacroName" (removed .) and got error Named argument not found. And get selected Key:=


Solution

  • In "ThisWorkbook", you will run code that is triggered by an event. I suggest you also put it in Workbook_Open instead of Workbook_Activate as you only need to store the shortcut once.

    So, in the VB Editor, open the "Project Explorer" if it is not (CTRL+R) and find "ThisWorkbook" in the folder "Microsoft Excel Objects". Here the code should look like this

    Private Sub Workbook_Open()
    
        ' CTRL + SHIFT + RIGHT
        Application.OnKey "+^{RIGHT}", "YourMacroName"
    
    End Sub
    

    Since, inside a Module (In the Project Explorer, right click on the folder "Modules" and select Insert > Module), put the macro "YourMacroName"

    Sub YourMacroName()
       Selection.Copy
       Sheets("V").Select
    End Sub
    

    Oh, and you should probably rename your procedure "YourMacroName" for something more obvious...