在excel中动态添加按钮到行中。

问题描述 投票:0回答:2

我是Excel宏编码的新手,我有一个需求,在Excel中,用户在A列中输入一些数值,当他退出屏幕后,应该在G列的同一行中生成一个新的按钮,标签与A列中的数值相同,并在该按钮上添加一个宏函数。

同时,如果用户删除了A列中一行的值,那么相应的按钮也应该被删除。

我试过某些论坛,但无法找到创建焦点退出按钮的代码。

请大家帮忙。

excel excel-vba vba
2个回答
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

你需要把它插入到工作表的代码模块中去

© www.soinside.com 2019 - 2024. All rights reserved.