Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to Sum a Number in a string 1

Status
Not open for further replies.

cantona

Technical User
May 20, 2001
121
GB
I have a field that contains data relating to active weeks in a year for a course being run. For example, the field may contain the following.. 01001011. The 1’s indicate that for that particular week the course is active, the 0’s indicate for that week the course isn’t running. I need to create a query that will search the Week_pattern field and add up how many occurrences of 1 there are, giving me the total number of active weeks. I know I probably need to use the Instr function somehow but unsure on how exactly to do this. Can anyone help?
 
This would be very easy indeed if you normalized. Anyway, I think you need a function:

[Code Typed, Not Tested]Function SumWeeks(fld)
If IsNull(fld) Then
SumWeeks=0
Exit Function
End If

For i=1 to Len(Trim(fld))
intTmp=intTmp+Val(Mid(fld,i,1))
Next

SumWeeks=intTmp
End Function[/code]



 
Hi Remou,

Thanks for the advice. Cant really do anything about the state of the tables though as they are part of a 3rd party application. Is there anyway of writing this as an expression instead? I only really need to count how many 1's appear in the Week_pattern field. So far ive been working along the lines of..

SUM(IIF(INSTR("1",[WEEK_PATTERN]),1,0)) but cant get it right. Im not really that skilled in this sort of thing!
 
Ok. There may just be a way. Try:

[tt]Len(Fld)-Len(Replace(fld,"1",""))[/tt]
 
Thanks Remou,

Thats exactly what i was after!

Youve saved me from a major headache!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top