看板 Visual_Basic 關於我們 聯絡資訊
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
catchtest:TextBox1.Text這些變數型態是String,無法直接相加 04/09 13:50
catchtest:你改的程式碼會對是因為/1後VB會自動幫你轉型 04/09 13:51
catchtest:可以改成Val(TextBox1.Text)這樣,就能直接相加了 04/09 13:52
catchtest:另外,這個應該不是VBA吧 04/09 13:53
catchtest:補充,Text直接相加會變成文字相接,如1 + 2 = 12 04/09 16:21