键入时在TextBox中设置数字格式 [英] Format numbers in TextBox as you type
问题描述
在键入时,是否可以通过格式化文本框(在用户窗体上)中的数字?
Is there is any way to format numbers in TextBox (on a UserForm) as you type?
通过这种方式,可以轻松查看正在输入的数字.
This way it makes easy to see what figure is being entered.
我想要的格式是:#,## 0.00
推荐答案
对于新手来说,这可能被认为是稍微高于平均水平的"高于平均水平"问题,因此我将回答这个问题:)
This could be considered a slightly "Above the Average" question in terms of difficulty for a newbie so I am going to answer this :)
VBA没有所谓的蒙版文本框",您可以在其中将格式设置为#,## 0.00
.您只能为接受密码而做一个带遮罩的文本框,但这完全是另一回事.
VBA doesn't have what you call a Masked Text Box where you can set formats as #,##0.00
. You can only do a masked textbox for accepting passwords but that is altogether a different thing.
这是我很快想到的.希望这就是你想要的吗?
Here is something I quickly came up with. Hope this is what you want?
Dim CursorPosition As Long
Dim boolSkip As Boolean
Dim countCheck As Long
Private Sub TextBox1_Change()
'~~> This avoids refiring of the event
If boolSkip = True Then
boolSkip = False
Exit Sub
End If
'~~> Get current cursor postion
CursorPosition = TextBox1.SelStart
boolSkip = True
'~~> Format the text
TextBox1.Text = Format(TextBox1.Text, "#,##0.00")
'~~> Re-position the cursor
If InStr(1, TextBox1.Text, ".") - 1 > 0 Then _
TextBox1.SelStart = InStr(1, TextBox1.Text, ".") - 1
End Sub
通过同时包含此代码,您可以将其提升到更高的水平.这样可以确保用户仅键入数字.
You can take it to a slightly higher level by including this code as well. This ensures that the user only types numbers.
'~~> Numeric Textbox with Decimal Check
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyDelete, _
vbKeyLeft, vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
If KeyAscii = 46 Then If InStr(1, TextBox1.Text, ".") Then KeyAscii = 0
Case Else
KeyAscii = 0
Beep
End Select
End Sub
实际操作
这篇关于键入时在TextBox中设置数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!