简体   繁体   中英

Excel VBA Text Boxes

I am trying to create a Calculator in excel VBA using a userform with two text boxes, I have just created the numpad and when I click on 1 for instance, it will input number 1 in text box 1 but when I select text box two and then select the number 1 again it will enter it back in text box 1 instead of text box 2 where my cursor was on. Anyone know how I can use something like setFocus or anything along those lines to enter the number in whatever textbox the cursor is set on, Thanks.

Private Sub CmdBtn1_Click()
    txt_Num1.Value = txt_Num1.Value + "1"
End Sub

I am looking for for the number to be inputted into whichever text box the cursor was set on when the number is clicked.

This is highly primitive but it should get you started in the right direction. This would be the code-behind in your userform.

Dim currentTextBoxName As String

Private Sub CommandButton1_Click()
  Dim currentControl
  Set currentControl = Controls(currentTextBoxName)
  currentControl.Value = "1"
End Sub

Private Sub TextBox1_Enter()
  currentTextBoxName = "TextBox1"
End Sub

Private Sub TextBox2_Enter()
  currentTextBoxName = "TextBox2"
End Sub

This assumes that your two textboxes are named 'TextBox1' and 'TextBox2'. Obviously there are much better ways (more foolproof) to pass the names of the textboxes on the TextBox_Enter event, but this shows you the basic premise.

And obviously, you would add code for the TextBox_Exit event to make sure values were not entered in the wrong textbox once the focus had left that TextBox.

When learning to write VBA code in the VBA IDE, it helps to use the dropdowns at the top of the code window: 在此输入图像描述

Those two dropdowns give you access to all the objects on your userform and their associated events. Super-helpful and often overlooked tool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM