0

I am new to Excel Macro Coding and I have a requirement in which, in Excel, the user enters some numeric value in the column A and as soon as he tabs out of the screen, a new button should be generated in the same row in column G with the label same as that of the value in Column A and a macro function will be added to the button.

Also, if the user deletes the value from the row in column A, then the corresponding button should also be removed.

I tried certain forums but am not able to find the code for creating the button on focus out.

Please help.

1 Answer 1

3

Try this code:

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

You need to insert it in the Code module of your worksheet.

Sign up to request clarification or add additional context in comments.

2 Comments

i, i tried the code..it worked sometimes and sometimes not...could you please help me exactly where will i place it and what it does...
It will work every time you're changing cell A1 in your worksheet - see the first line of code. If you want a different/large range, change "A1"according to your needs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.