简体   繁体   English

Excel VBA文本框

[英]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. 我正在尝试使用带有两个文本框的userform在excel VBA中创建一个计算器,我刚创建了numpad,当我点击1时,它会在文本框1中输入数字1,但是当我选择文本框2和然后再次选择数字1,它将在文本框1中输入它,而不是我的光标所在的文本框2。 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. 任何人都知道如何使用setFocus之类的东西或沿着这些行的任何东西在光标设置的任何文本框中输入数字,谢谢。

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'. 这假定您的两个文本框名为“TextBox1”和“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. 显然,有更好的方法(更加万无一失)传递TextBox_Enter事件上文本框的名称,但这显示了基本前提。

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. 显然,您将为TextBox_Exit事件添加代码,以确保在焦点离开TextBox后未在错误的文本框中输入值。

When learning to write VBA code in the VBA IDE, it helps to use the dropdowns at the top of the code window: 学习在VBA IDE中编写VBA代码时,有助于使用代码窗口顶部的下拉列表: 在此输入图像描述

Those two dropdowns give you access to all the objects on your userform and their associated events. 通过这两个下拉菜单,您可以访问userform上的所有对象及其相关事件。 Super-helpful and often overlooked tool. 超级有用且经常被忽视的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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