我是Excel宏编码的新手,我要求在Excel中,用户在A列中输入一些数值,并且一旦他从屏幕上跳出,就应该生成一个新的按钮。 G列中的相同行,其标签与A列中的值相同,并且宏功能将添加到按钮中。
此外,如果用户从A列的行中删除该值,则也应删除相应的按钮。
我尝试了某些论坛,但无法在焦点上找到创建按钮的代码。
请帮忙。
答案 0 :(得分:3)
试试这段代码:
Private Const mcStrButtonAddress As String = "D3" 'The cell or range which is used for top and left position of button
Private Const mcStrMacroToRun As String = "Macro1"
Private Const mcStrButtonName As String = "Button" 'Used internally to delete button
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.Intersect(Target, Range("A1")) Is Nothing Then Exit Sub
'To disable endless loop
Application.EnableEvents = False
'Delete button
On Error Resume Next
Me.Buttons(mcStrButtonName).Delete
On Error GoTo 0
'Insert button
With Me.Buttons.Add( _
Range(mcStrButtonAddress).Left, _
Range(mcStrButtonAddress).Top, _
Range(mcStrButtonAddress).Width, _
Range(mcStrButtonAddress).Height)
'Configure button
.Name = mcStrButtonName
.Characters.Text = Target.Value
.OnAction = mcStrMacroToRun
End With
'Reenable events
Application.EnableEvents = True
End Sub
您需要将其插入工作表的代码模块中。