vba 用户表单文本框中的格式编号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28860017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:25:57  来源:igfitidea点击:

Format number in userform textbox

excelvba

提问by 5kids

I have a texbox in a userform in which the user will input numbers. Those numbers will be tranfered to an Excel spreadsheet for calculation.

我在用户表单中有一个 texbox,用户将在其中输入数字。这些数字将被传输到 Excel 电子表格进行计算。

I want that when the user inputs numbers in the Textbox it displays as a number in a specific format.

我希望当用户在文本框中输入数字时,它以特定格式显示为数字。

For example: 2000000, I want it as 2,000,000.00 in the Textbox.

例如:2000000,我希望它在文本框中为 2,000,000.00。

I tried:

我试过:

Public Sub UserForm_Initialize()    
    TextBox1 = Format(TextBox1, "$#,##0.00")
End Sub

But the Userform doesn't change.

但是用户表单不会改变。

If I try the following

如果我尝试以下

Private Sub TextBox1_Change()
    TextBox1 = Format(TextBox1, "$#,##0.00")
End Sub

The userform shows the number adequately, but then updates the Excel spreadsheet with a text format instead of number and the calculation doesn't run.

用户窗体充分显示数字,但随后使用文本格式而不是数字更新 Excel 电子表格,并且计算不会运行。

回答by Jeanno

Here is a workaround, use the second subroutine to get the value in a string format.

这是一种解决方法,使用第二个子例程以字符串格式获取值。

Private Sub TextBox1_Change()
    TextBox1 = Format(TextBox1, "$#,##0.00")
End Sub

Then convert the format of the cell where this value was assigned. Range("A1").Value = CDbl(Range("A1").Value)

然后转换分配此值的单元格的格式。 Range("A1").Value = CDbl(Range("A1").Value)

回答by Minh

Double click on textbox and then You should use AfterUpdate event

双击文本框,然后您应该使用 AfterUpdate 事件

Private Sub txtmoney_AfterUpdate()
Me.txtmoney.Value = Format(Me.txtmoney.Value, "$#,##0.00")

End Sub

回答by Tyk

Just format the destination columns to the number format, you won't have to bother wih the text box..

只需将目标列格式化为数字格式,您就不必为文本框烦恼了..

回答by Daniel

Use the exit event to format, as change event tries to reformat as you type and may not allow you to even enter the whole number.

使用退出事件进行格式化,因为更改事件会在您键入时尝试重新格式化,甚至可能不允许您输入整数。

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    TextBox1 = Format(TextBox1, "$#,##0.00")
End Sub