gpt4 book ai didi

vba - 在运行时向工作表添加命令按钮并定义事件

转载 作者:行者123 更新时间:2023-12-04 03:08:15 25 4
gpt4 key购买 nike

我试图在运行时在我的工作表中添加一个 ActiveX 命令按钮。命令按钮的数量将取决于工作表中的行数。我计划在命令按钮属性中提供 x 和 y 坐标以正确定位它们。我知道我们可以通过这种方式在用户表单中插入命令按钮。

Private Sub CommandButton1_Click()

Me.Controls.Add _
"Forms.CommandButton.2", "CopyOf"
End Sub

我们如何在工作表(而不是用户表单)中插入命令按钮。 Worksheets("abc").Add 不起作用。还有如何为它们定义独立的点击事件。例如,如果我单击一个命令按钮,它应该告诉我它在哪一行。

谢谢

------------更新----------------------------

因此,我可以根据工作表中的行数在所需位置动态添加命令按钮。

Private Sub addb3(ByVal rows_present_alerts As Integer)
Dim topcounter As Double
topcounter = 15.75
For i = 2 To rows_present_alerts ' The first row has the column headers
With Worksheets("abc").OLEObjects
.Add(ClassType:="Forms.CommandButton.1", Link:=False _
, DisplayAsIcon:=False, Left:=509.25, Top:=topcounter, Width:=48, Height:=14.25 _
).Select
End With
topcounter = topcounter + 15 ' (not sure this approach will work in monitors with diff screen resolution but anyways)
Next i
End Sub

我想为每个命令按钮分配点击事件。当我单击命令按钮时,它应该告诉我它在哪一行。

最佳答案

它可以提供帮助,您可能还会想知道如何访问它;

Sub addButton()

Dim myButton As OLEObject



Set myButton = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Left:=0, Top:=300, Height:=20, Width:=200)

myButton.Placement = XlPlacement.xlFreeFloating

myButton.Object.Caption = "Click Me..."

myButton.Name = "DynamicButton"


End Sub

Private Sub DynamicButton_Click()



MsgBox "Hello sheet"



End Sub

关于vba - 在运行时向工作表添加命令按钮并定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8250050/

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