How to perform .Onkey Event in an Excel Add-In created with Visual Studio 2010?

后端 未结 4 638
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 18:23

I am creating an Excel Add-In using Visual Studio 2010. I would like to run some code when users clicks a combination of keys.

Here is the code I have got

         


        
4条回答
  •  一整个雨季
    2020-12-03 18:53

    First thing A1, A2, A3 are considered as cell address.

    1. Create .xlsm file and add these VBA code

      Sub AOne()
      MsgBox "Message from AOne"
      End Sub
      
      Sub ATwo()
      MsgBox "Message from ATwo"
      End Sub
      
      Sub AThree()
      MsgBox "Message from AThree"
      End Sub
      
    2. Now create a Excel Workbook project in Visual studio and add existing file and choose the above created .xlsm file

      private void ThisWorkbook_Startup(object sender, System.EventArgs e)
      {
          EnableShortCut();
      }
      
      private void ThisWorkbook_Shutdown(object sender, System.EventArgs e)
      {
      }
      
      public void EnableShortCut()
      {
          Excel.Application app = Globals.ThisWorkbook.Application;
          app.OnKey("+^{U}", "AOne"); //action A1 should be performed when user clicks  Ctrl + Shift + U
          app.OnKey("+^{L}", "ATwo");//action A2 should be performed when user clicks  Ctrl + Shift + L
          app.OnKey("+^{P}", "AThree"); //action A3 should be performed when user clicks  Ctrl + Shift + P
      }
      

    Run your project this should work, Application.OnKey in Excel or Application.Keybindings in Word takes the Macro name as parameter.

    Check my answer for using shortcut keys in Word here

提交回复
热议问题