Results 1 to 2 of 2

Thread: Adding up numbers in a String

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2002
    Location
    Australia
    Posts
    1

    Adding up numbers in a String

    I'm stuck with this problem:
    Say i've got a string with "1234" in it, and i need to add up all those numbers (so 1+2+3+4=10). How do I get vb to do that.
    I know the answers probably very simple - but Im stuck!

    Thanks a lot!

  2. #2
    PowerPoster beachbum's Avatar
    Join Date
    Jul 2001
    Location
    Wollongong, NSW, Australia
    Posts
    2,274
    Hi
    Here is a quick way
    VB Code:
    1. Private Sub Command1_Click()
    2.     Dim MyString As String
    3.     Dim Counter As Long
    4.     Dim Total As Long
    5.    
    6.     MyString = "1234" 'String to add up
    7.     Total = 0 'Starting value
    8.     For Counter = 1 To Len(MyString) 'Loop thru all chars in string (ie 4 chars)
    9.         Total = Total + CLng(Mid$(MyString, Counter, 1)) 'Add numeric val of each character
    10.     Next
    11.     MsgBox Total 'Show total
    12. End Sub
    Stuart Laidlaw
    Brightspark Financial Software
    http://www.gstsmartbook.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width