0

我是 Excel 宏编码的新手,我有一个要求,在 Excel 中,用户在 A 列中输入一些数值,一旦他跳出屏幕,应该在同一行中生成一个新按钮G 列的标签与 A 列中的值的标签相同,并且将在按钮中添加一个宏功能。

此外,如果用户从 A 列的行中删除值,则相应的按钮也应该被删除。

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

请帮忙。

4

1 回答 1

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

您需要将其插入工作表的代码模块中。

于 2013-02-13T21:07:00.840 回答