EXCEL VBA:使用正在动态创建的按钮的 onclick 属性调用事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15379923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:00:20  来源:igfitidea点击:

EXCEL VBA: calling an event with onclick property of a button which is being created on the fly

excelvbaruntimesyntax-error

提问by vishal balwani

I am creating a excel VBA userform which requires many buttons to be created on the fly (ie as the requirement may be, runtime). I want to assign a subroutine to these buttons so that when they are clicked a subroutine should execute.

我正在创建一个 excel VBA 用户表单,它需要即时创建许多按钮(即根据要求,运行时)。我想为这些按钮分配一个子例程,以便在单击它们时应该执行一个子例程。

this is what I want to do

这就是我想要做的

Set obj4 = usrform.Controls.Add("forms.commandbutton.1")
obj4.Height = 17
obj4.Left = 450
obj4.Top = 75 
obj4.Font.Size = 11
obj4.Name = "compare" & (j - i) 'j and i are some variables in the code
obj4.Caption = "Compare!"
obj4.onclick =  abcd

public sub abcd()
'some code here
end sub

but this code is not running. I read somewhere that here I cannot call a subroutine but a function. My problem is that I want a subroutine only as I dont intend to get something in return from it. But still for trial purpose I made abcd() a function in the above code and then my code was running but unsuccessfully as it was executing the function abcd without the need of button getting pressed.

但这段代码没有运行。我在某处读到这里我不能调用子程序,而是调用函数。我的问题是我只想要一个子程序,因为我不打算从中得到什么回报。但仍然出于试验目的,我在上面的代码中创建了 abcd() 一个函数,然后我的代码正在运行但没有成功,因为它在执行 abcd 函数时不需要按下按钮。

Can anyone help me with this? I have searched a lot for this on internet in various forums.

谁能帮我这个?我在互联网上的各种论坛上搜索了很多。

回答by grahamj42

Don't get hung up on subroutine v. function: if you don't set the return value of a function, it's the same as a subroutine.

不要纠结于子例程与函数:如果你不设置函数的返回值,它和子例程是一样的。

When you set the onClick property, you give it the name of the function as a string obj4.onclick = "abcd"otherwise it will execute the function and save the return value.

当您设置 onClick 属性时,您将函数的名称作为字符串提供给它,obj4.onclick = "abcd"否则它将执行该函数并保存返回值。