作者j76992001 (人缘有待等)
看板Visual_Basic
标题[VBA ] 字串转换成数值的问题
时间Thu Apr 9 12:07:54 2009
Public Class Form1
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox1.TextChanged
Dim x
x = Val(TextBox1.Text)
If x < 0 Or x > 100 Then
TextBox1.BackColor = Color.Red
Else
TextBox1.BackColor = Color.AliceBlue
End If
End Sub
Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox3.TextChanged
Dim y
y = Val(TextBox3.Text)
If y < 0 Or y > 100 Then
TextBox3.BackColor = Color.Red
Else
TextBox3.BackColor = Color.AliceBlue
End If
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox2.TextChanged
Dim z
z = Val(TextBox2.Text)
If z < 0 Or z > 100 Then
TextBox2.BackColor = Color.Red
Else
TextBox2.BackColor = Color.AliceBlue
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim sum As Double
sum = (TextBox1.Text + TextBox2.Text + TextBox3.Text) / 3
Label5.Text = sum
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
If MsgBox("是否确定离开此程式?", MsgBoxStyle.YesNo, "关闭程式") =
MsgBoxResult.Yes Then
End
End If
End Sub
End Class
整个动作在於透过表单输入三个数值,再透过Button求平均,但是在Button求平均时候,
却发生了TextBox1跟TextBox2数值上的错误(T1数值放大了100倍,T2放大了10倍)
但是我如果在sum = (TextBox1.Text + TextBox2.Text + TextBox3.Text) / 3
改成sum = (TextBox1.Text/1 + TextBox2.Text/1 + TextBox3.Text/1) / 3
结果就是正确的了,想请问版上各位,是我哪一个的事件的程式有错误呢??
--
曾经沧海难为水~~
~~ 除却巫山不是云
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 122.118.70.79
1F:→ catchtest:TextBox1.Text这些变数型态是String,无法直接相加 04/09 13:50
2F:→ catchtest:你改的程式码会对是因为/1後VB会自动帮你转型 04/09 13:51
3F:→ catchtest:可以改成Val(TextBox1.Text)这样,就能直接相加了 04/09 13:52
4F:→ catchtest:另外,这个应该不是VBA吧 04/09 13:53
5F:→ catchtest:补充,Text直接相加会变成文字相接,如1 + 2 = 12 04/09 16:21