PDA

View Full Version : Solved: Loop to Count Form Fields



BostonVB
08-11-2011, 10:04 AM
Hello,
I'm trying to figure out a way to count the responses ("Y") of 15 different forms Fields.

FormFields= ProbMed_1,ProbMed_2, ProbMed_n...15

I simply need to count the number of the ProbMed_n form fields with a Y and put that total in form field 'TotProblemMeds'

The code I'm starting with is:

Sub Recalc_Med_Problems()

Dim i, ProblemMeds As Integer
Dim TotProblemMeds, iStr, BkMark As String

ProblemMeds = 0
i = 1

Do While i < 16
iStr = Str(i)
BkMark = "ProbMed_" & iStr
TotProblemMeds = ActiveDocument.FormFields(BkMark).Result
If TotProblemMeds = "Y" Then ProblemMeds = ProblemMeds + 1
i = i + 1
Loop
' Place the total Problem Medications found into the TotProblemMeds field on the document.
ActiveDocument.FormFields("TotProblemMeds").Result = ProblemMeds
End Sub


Thoughts?

Frosty
08-11-2011, 11:01 AM
I'd like to point out a couple of flaws in your structure:

Dim i, ProblemMeds As Integer
doesn't give you two integers... it gives you a variant (i) and an integer (ProblemMeds). Same with the next line.

Personally, I'm not a fan of multi-dim lines, and nor am I a fan of single line If statements, but that's a style thing. Feel free to go back to your style, but since I rewrote it, you get my style ;)

Dim i as Integer, ProblemMeds as Integer
is what you want. Same for the next line.

Other than that, you don't need to set variables to their default values (ProblemMeds, defined as an integer, starts at 0... you don't need to set it to 0 unless you don't define its type, at which point it will be a variant/empty until you set it to 0, at which point it will be a Variant/Integer).

Here's a simpler version of what you're doing (you don't need 5 variables, when 3 will do)... using a for loop instead of a do loop...


Sub Recalc_Med_Problems()
Dim i As Integer
Dim ProblemMeds As Integer
Dim BkMark As String

For i = 1 To 15
'get your bookmark name
BkMark = "ProbMed_" & CStr(i)
If ActiveDocument.FormFields(BkMark).Result = "Y" Then
ProblemMeds = ProblemMeds + 1
End If
Next

' Place the total Problem Medications found into the TotProblemMeds field on the document.
ActiveDocument.FormFields("TotProblemMeds").Result = CStr(ProblemMeds)
End Sub

BostonVB
08-11-2011, 11:16 AM
No, your style is great! this works perfectly. Thank you for your time and great explaination!

Thanks!