使用 Excel 表格添加数字

Adding numbers using Excel Forms

我创建了一个 Excel 表单,其中有五个文本框。这些文本框接受任何数值。一旦输入了五个数字,就会有第六个文本框显示这些值的总和。这些值的总和应始终为 100%。这是我的代码:

Private Sub TextBox1_Change()

Dim Value As Single

Value = Val(TextBox1.Value) + Val(TextBox2.Value) + Val(TextBox3.Value) + Val(TextBox4.Value) + Val(TextBox5.Value)

TextBox6.Value = Value

End Sub

我对所有文本框更改事件使用相同的代码。不幸的是,这是行不通的。当我输入 10203040 作为输入时,结果不是显示 100%,而是显示 10203040

我做错了什么?

我相信您需要使用的函数是 CDblCSng,它可以转换为双精度或单精度浮点数。它不会处理输入的空白​​或非数字数据,因此您可能需要先检查输入的无效数据。这样的事情应该有效:

Value = 0
If IsNumeric(TextBox1.Value) Then Value = Value + CSng(TextBox1.Value)
If IsNumeric(TextBox2.Value) Then Value = Value + CSng(TextBox2.Value)
If IsNumeric(TextBox3.Value) Then Value = Value + CSng(TextBox3.Value)
If IsNumeric(TextBox4.Value) Then Value = Value + CSng(TextBox4.Value)
If IsNumeric(TextBox5.Value) Then Value = Value + CSng(TextBox5.Value)

TextBox6.Value = Value