English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

問一下 各位大大

我要運算一個數值 010620011770
單數 :
第1個數值 + 第3個數值 + 第5個數值 + 第7個數值 + 第9個數值 + 第11個數值 = 解
如 : 0+0+2+0+1+7=10

雙數 :
第2個數值 + 第4個數值 + 第6個數值 + 第8個數值 + 第10個數值 + 第12個數值 = 解
如: 1+6+0+1+7+0=15

我只要在 text1 裡面打010620011770 就會算出在 label1裡面(單) label2裡面(雙)

2006-06-28 12:40:02 · 3 個解答 · 發問者 冰哥 1 in 電腦與網際網路 程式設計

3 個解答

這段是我剛寫的,相信應該會比你多數同學寫的棒.我的code有
兩個優點:

1.一邊打字一邊就會變! 不必另外按鍵
2.具容錯功能,如果打了非數字進去的話程式不會錯誤

程式碼如下:(ps:使用全形容白輔助排版)

Private Sub Text1_Change()
 Dim NumStr As String, StrLen As Long, Char As String, Sum As Long
 NumStr = Trim(Text1.Text)
 StrLen = Len(NumStr)
 If StrLen > 0 Then
  For i = 1 To StrLen
    Char = Mid(NumStr, i, 1)
    If Char < "0" Or Char > "9" Then
      Label1.Caption = "非數字!"
      Label2.Caption = "非數字r!"
      Exit Sub
    End If
  Next
  For i = 1 To StrLen Step 2
    Sum = Sum + CLng(Mid(NumStr, i, 1))
  Next
  Label1.Caption = Sum
  Sum = 0
  For i = 2 To StrLen Step 2
    Sum = Sum + CLng(Mid(NumStr, i, 1))
  Next
  Label2.Caption = Sum
 End If
End Sub

底下是可直接 Copy 到 VB 裡面用的碼:
(PS: 要先在 Form 上面放 label1 和 label2 和 text1 喔~)

Private Sub Text1_Change()
Dim NumStr As String, StrLen As Long, Char As String, Sum As Long
NumStr = Trim(Text1.Text)
StrLen = Len(NumStr)
If StrLen > 0 Then
For i = 1 To StrLen
Char = Mid(NumStr, i, 1)
If Char < "0" Or Char > "9" Then
Label1.Caption = "非數字!"
Label2.Caption = "非數字!"
Exit Sub
End If
Next
For i = 1 To StrLen Step 2
Sum = Sum + CLng(Mid(NumStr, i, 1))
Next
Label1.Caption = Sum
Sum = 0
For i = 2 To StrLen Step 2
Sum = Sum + CLng(Mid(NumStr, i, 1))
Next
Label2.Caption = Sum
End If
End Sub

2006-06-28 22:12:10 補充:
W & 愁 的 code 雖然漂亮,但仍存 BUG. 如果用戶打了123然後按 mouse 右鍵選貼上 (貼上了 ABC )然後再打 123 , 程式就會 Error 掉. 在視窗環境下光用KeyPress 檢查並不是很保險的

2006-06-28 13:27:02 · answer #1 · answered by LeeDashOne 5 · 0 0

Private Sub Text1_Change()   Label1 = "":   Label2 = ""   For i = 1 To Len(Text1)      With Me.Controls("label" & IIf(i Mod 2 = 0, 2, 1))         .Caption = Val(.Caption) + Val(Mid(Text1, i, 1))      End With   NextEnd Sub'若不想讓使用者輸入非數字字元,加入以下這段Private Sub Text1_KeyPress(KeyAscii As Integer)If InStr("0123456789", Chr(KeyAscii)) = 0 And KeyAscii <> 8 Then KeyAscii = 0End Sub

2006-06-28 14:21:13 · answer #2 · answered by ? 6 · 0 0

Private Sub Text1_Change()        Dim I As Integer, A(1) As Integer                '利用Mod判斷是奇數還是偶數直接放到Label        For I = 1 To Len(Text1)            A(I Mod 2) = A(I Mod 2) + Val(Mid(Text1, I, 1))        Next        Label1 = A(1): Label2 = A(0)End Sub'限制只能輸入數字Private Sub Text1_KeyPress(KeyAscii As Integer)        If InStr("0123456789" & Chr(8), Chr(KeyAscii)) = 0 Then KeyAscii = 0End Sub

2006-06-28 14:20:33 · answer #3 · answered by W.J.S. 7 · 0 0

fedest.com, questions and answers