在运行子服务器之前,从子服务器调用按钮单击事件而不知道按钮的名称

时间:2017-08-22 17:12:10

标签: excel vba events click

Sub中,我想触发一个Click事件。对于给定的Button,例如ButtonCommand1,我可以通过运行代码来执行此操作:

    Sub test()

         Call Sheet1.ButtonCommand1_Click

    End sub

ButtonCommand1_Click是用Public Sub写的Sheet1

但是,我的问题是,在运行sub本身之前,我不知道要点击的Button的名称。所以我需要这样的东西:

    Sub test()

         Dim i As Integer
         Dim button As String

         i = 'SOMETHING
         button = "ButtonCommand" & i 

         Call Sheet1.button_Click

    End sub

,同样,Sub Sheet1.button_Click已经包含在Sheet1中作为所有Public Sub的{​​{1}}。

我尝试了几个选项,即将按钮设置为i并使用Objec集合进行播放,以便: Shapes还尝试通过执行Set button = shapes.range(Array("ButtonCommand" & i)) AND i然后运行shapes.range(Array("ButtonCommand" & i)).select来选择正确的形状。但没有任何作用。谢谢你的帮助!

4 个答案:

答案 0 :(得分:5)

您不会调用事件处理程序。处理程序处理事件,它们由VBA运行时调用以响应某些特定事件。

“手动”调用事件处理程序是任何语言的反模式,VBA也不例外。默认情况下,事件处理程序为int size = strings.size(); int[] result = new int[size]; int index = 0; for(int newLength = result.length; index < newLength; ++index) { String numberRaw = strings.get(index); int parsedNumber = Integer.parseInt(numberRaw); result[index] = parsedNumber; }

很难准确说出你在使用示例代码做了什么,但是说你有这个:

Private

然后在其他地方,你想要调用那个点击处理程序 - 不要!改为调用Private Sub Button1_Click() DoStuff End Sub

答案 1 :(得分:4)

使用CallByName

Sub test()

    Dim strName As String
    Dim i       As Long

    i = 1

    strName = "Button" & i & "_Click"
    CallByName Sheet1, strName, VbMethod


End Sub

答案 2 :(得分:1)

Application.Run "ButtonCommand" & i & "_Click"应该这样做。

答案 3 :(得分:1)

我刚刚解决了这个问题,虽然 cyboashu 的回答让我非常接近找到这个问题,但我偶然发现了另一种方法,这是我能够做到的唯一方法。 (我的命令按钮通常是隐藏的并位于受保护的工作表上 - 不确定这是否对我的工作有影响。)

从您调用的 Sub 中,请使用以下内容:

Sub Test()
    'Took me directly to the subroutine of the CommandButton using:
    Sheet1.CommandButton1 = True
End Sub