问题
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.
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.
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.
回答1:
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)
回答2:
Double click on textbox and then You should use AfterUpdate event
Private Sub txtmoney_AfterUpdate()
Me.txtmoney.Value = Format(Me.txtmoney.Value, "$#,##0.00")
End Sub
回答3:
I solved it writing this:
Range("A1").value = textbox1.value
instead of this
Range("A1").value = textbox1
In my case the .value
made the difference.
回答4:
Just format the destination columns to the number format, you won't have to bother wih the text box..
回答5:
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
来源:https://stackoverflow.com/questions/28860017/format-number-in-userform-textbox