gpt4 book ai didi

excel - 将宏分配给以编程方式添加的 vba 按钮

转载 作者:行者123 更新时间:2023-12-04 22:18:02 25 4
gpt4 key购买 nike

我尝试以编程方式将 VBA 按钮添加到我的工作簿。
我可以创建它,但由于某种原因,我无法在其上链接宏。
我总是收到错误消息:

Cannot run the macro "xxx". the macro may not be available in this WB or all macros may be disabled


这是我的代码:
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
有谁知道出了什么问题?

最佳答案

我建议使用以下语法以避免奇怪的命名问题:
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
在一个模块 CommandButtonActions
Option Explicit

Public Sub FolderSelectorButton_Click()
MsgBox Application.Caller
End Sub
您从按钮调用的过程必须在普通模块中,并且必须是 Public (这实际上是默认的)。

关于excel - 将宏分配给以编程方式添加的 vba 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66982385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com