[英]Assign macro to a programmatically added vba button
I try to programmatically adding a VBA button to my workbook.我尝试以编程方式将 VBA 按钮添加到我的工作簿中。 I can creat it but for some reason I can't link a macro on it.
我可以创建它,但由于某种原因,我无法在其上链接宏。
I always get the error message:我总是收到错误消息:
Cannot run the macro "xxx".
无法运行宏“xxx”。 the macro may not be available in this WB or all macros may be disabled
宏可能在此 WB 中不可用或所有宏可能被禁用
Here is my code:这是我的代码:
Private Sub Workbook_Open()
'Remove all old buttons of the worksheet
ActiveSheet.Buttons.Delete
'Restore Folder selector button
Set t = ActiveSheet.Range(Cells(2, 1), Cells(2, 1))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "FolderSelector"
.Caption = "Folder selector"
.Name = "Folder Selector"
End With
End Sub
Sub FolderSelector()
MsgBox Application.Caller
End Sub
Is there anyone know what's wrong?有谁知道出了什么问题?
I recommend the following syntax to avoid odd naming issues:我建议使用以下语法以避免奇怪的命名问题:
In ThisWorkbook
在
ThisWorkbook
中
Option Explicit
Private Sub Workbook_Open()
'Remove all old buttons of the worksheet
ActiveSheet.Buttons.Delete
'Restore Folder selector button
Dim t As Range
Set t = ActiveSheet.Cells(2, 1) 'note this is shorter and the same as .Range(Cells(2, 1), Cells(2, 1))
Dim btn As Object
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "FolderSelectorButton_Click"
.Caption = "Folder selector"
.Name = "FolderSelectorButton"
End With
End Sub
In a module CommandButtonActions
在一个模块
CommandButtonActions
Option Explicit
Public Sub FolderSelectorButton_Click()
MsgBox Application.Caller
End Sub
The procedure you call from the button has to be in a normal module and it has to be Public
(which is actually default).您从按钮调用的过程必须在普通模块中,并且必须是
Public
的(实际上是默认的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.