Issue with buttons and textboxes

91 Views Asked by At

I'm trying to create a wordle game but I'm not sure how to display strings textbox when button is clicked. For example, in this

screenshot,

when letter "A" is clicked, the first row of the first textbox will display "A". If letter "B" is clicked, the first textbox will display "B" etc. I want to make it so that it can spell out a word using the buttons and textboxes(grid). I tried

 tb1.text = cmdbtn1.caption

but I didn't get the expected result. I'm not sure if I have to use for loop to do so. Please give some suggestions. Thanks.

This is one of the button events that is used throughout the program

Private Sub cmdbtn1_Click()
  'code here
end sub
1

There are 1 best solutions below

6
On

We need to track the active Textbox. If all the controls directly on the Userform, the Userform's ActiveControl changes to the Button when it is clicked. We could track the active Textbox using each Textboxes' Exit event.

Private ActiveCheckbox As MSForms.TextBox

Private Sub tb1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Set ActiveCheckbox = tb1
End Sub

Private Sub tb2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Set ActiveCheckbox = tb2
End Sub

But this is a lot of extra work. Alternately, we can place all the textboxes in a Frame control. The Frame's ActiveControl will not change when a Button outside of the Frame is clicked.

Userform Example

We also need call a subroutine to process the button clicks.

Private Sub UpdateWordleTextbox(btn As MSForms.CommandButton)
    If IsNull(Frame1.ActiveControl) Then Exit Sub
    If Not (Frame1.ActiveControl.Name Like "tb#" Or Frame1.ActiveControl.Name Like "tb##") Then Exit Sub
    Frame1.ActiveControl.Value = btn.Caption
    
    Dim CurrentTextBoxIndex As Long
    CurrentTextBoxIndex = Replace(Frame1.ActiveControl.Name, "tb", "")
    
    If CurrentTextBoxIndex = 20 Then CurrentTextBoxIndex = 0
    CurrentTextBoxIndex = CurrentTextBoxIndex + 1
    
    Frame1.Controls("tb" & CurrentTextBoxIndex).SetFocus
    
End Sub


Private Sub CommandButton1_Click()
  UpdateWordleTextbox CommandButton1
End Sub

Private Sub CommandButton2_Click()
  UpdateWordleTextbox CommandButton2
End Sub

Private Sub CommandButton3_Click()
  UpdateWordleTextbox CommandButton1
End Sub

Private Sub CommandButton4_Click()
  UpdateWordleTextbox CommandButton1
End Sub