VBA Pass arguments with .onAction

后端 未结 2 498
你的背包
你的背包 2020-12-06 18:59

this is how my sub looks like:

Sub InsertRowWithContent(rowNo As Long)

This is my .onAction:

.OnAction = \"\'InsertRowWithC         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 19:15

    You need to add a space after your Sub name, like this:

    .OnAction = "'InsertRowWithContent " & C & "'"
                                      ^^^^^^^^^^
    

    EDIT

    Also, since you're passing a Long parameter, you shouldn't enclose it in quotes.

    EDIT 2

    OK, this will require some special sauce (code). I've been experimenting and I got the following to work.

    In the Sheet1 Excel object:

    Option Explicit
    
    Sub DestroyToolbar()
    
      Application.CommandBars("DoomBar").Delete
    
    End Sub
    
    Sub MakeToolbar()
    
      Dim C As Long
      C = 100
    
      With Application
        .CommandBars.Add(Name:="DoomBar").Visible = True
        With .CommandBars("DoomBar")
          .Controls.Add Type:=msoControlButton, ID:=2950, Before:=1
          With .Controls(1)
            .OnAction = "'PressMe " & C & "'"
          End With
        End With
      End With
    
    End Sub
    

    In a new standard code module, add this:

    Public Sub PressMe(C As Long)
    
      With Application.CommandBars("DoomBar")
        With .Controls(1)
          MsgBox "The value of C that was passed to this macro is: " & C
        End With
      End With
    
    End Sub
    

    If you run MakeToolbar, it will create a new toolbar in the "Add-ins" ribbon. To remove it, you can run DestroyToolbar.

    Once the toolbar is in place, then clicking the button should display a messagebox with the value of C (in my example, 100).

    I've tested the above in Excel 2010 and it worked, in a brand new .xlsm file.

提交回复
热议问题