Modify Last Selected Button

Asked

Viewed 68 times

0

I have a Userform containing multiple selection buttons 1-20.

When I press the Tingirred or Tingirazul button the last selected button should be dyed red or blue. Could someone help me draw up this sub?

  • Welcome to Stackoverflow. Take a look at this link to understand a little of the functioning of the community and how to better elaborate the questions.

  • Provide as much detail as possible to help others help you. Post a screen print, a snippet of code you’ve already made, etc...

1 answer

1


It will be necessary to use Class modules to accomplish this in a generic way and a form.

Árvore do VBE contendo um formulário e um módulo de classe

Form

An example with the following Form:

Formulário contendo 1 Label e 4 CommandButton

In which properties Name and Caption are the same in the image example.

Containing 4 buttons for testing and a label to store the value of the last clicked button.

Follow the code by initializing the class module in the form and making the label invisible.

Private collBtns As Collection
Private Sub UserForm_Initialize()
    'Crédito: www.andypope.info
    '         www.cpearson.com/excel/Events.aspx
    Dim cls_btn As Classe1
    Set collBtns = New Collection
    Me.Label1.Visible = False
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "CommandButton" Then
            Set cls_btn = New Classe1
            Set cls_btn.btn = ctrl
            collBtns.Add cls_btn, CStr(collBtns.Count + 1)
        End If
    Next ctrl
End Sub

Class module

This code is inserted in the class module Classe1

    Public WithEvents btn As MSForms.CommandButton

Private Sub btn_Click()
    Dim ultimo_botao As MSForms.Control
    Set ultimo_botao = UserForm1.Controls(UserForm1.Label1.Caption)
    If btn.Name = "TingirVermelho" Then
        ultimo_botao.BackColor = RGB(255, 0, 0)
        ultimo_botao.ForeColor = RGB(255, 255, 255)
    ElseIf btn.Name = "TingirAzul" Then
        ultimo_botao.BackColor = RGB(0, 0, 255)
        ultimo_botao.ForeColor = RGB(255, 255, 255)
    Else
        UserForm1.Label1.Caption = btn.Name
    End If
End Sub

In this, the button clicks event is declared in btn_Click().

If the button name is "TingirVermelho" or "TingirAzul", changes the color of the last button selected with .BackColor and .ForeColor. Other changes can be made on the button. See Button Properties

Otherwise, store the button name in Label1.

Upshot

Resultado em Gif com LICEcap

  • 1

    Thank you so much! It all worked out in my project.

  • Dear friend, could you help me now with another question?

  • https://answall.com/questions/325745/como-fazer-para-abram-um-userform-com-o-mesmo-nome-de-um-bot%C3%A3o-linguagem-vba

Browser other questions tagged

You are not signed in. Login or sign up in order to post.