Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MessageBox.Show (SommeChiffre(1234))
MessageBox.Show (SommeChiffre("1234"))
MessageBox.Show (SommeChiffre("12test34"))
End Sub
' marche avec tout type de numérique:
' Byte, Integer, Long, Double, Décimal, (chaîne mais avec restriction)
Private Function SommeChiffre(ByVal nombre As Object) As Long
Dim Result As Long
Dim tmp As Long
'On place une gestion d'erreur si caractere
Try
Dim N As String = nombre.ToString
For i As Integer = 0 To N.Length - 1
If Long.TryParse(N.Substring(i, 1), tmp) Then
Result += tmp
End If
Next
Catch ex As Exception
Result = -1
End Try
Return Result
End Function