Adding Form Fields /w VBA

J

jbc

Hi,

I'm trying to add up 3 numbers that are stored in form fields. I'm testing
it on a very simple document with the following code. It is working fine
except when I leave a form field blank. I formatted the form fields for
numbers. What am I missing?

Sub AddMeUp()

Dim intOne As Integer
Dim intTwo As Integer
Dim intThree As Integer
Dim Total As Integer

intOne = ActiveDocument.FormFields("text1").Result
intTwo = ActiveDocument.FormFields("text2").Result
intThree = ActiveDocument.FormFields("text3").Result

Total = intOne + intTwo + intThree

MsgBox Total

End Sub

Thanks.

jbc
 
S

Sabaka

Try this:

Sub AddMeUp()

Dim intOne As Integer
Dim intTwo As Integer
Dim intThree As Integer
Dim Total As Integer

If IsNumeric(ActiveDocument.FormFields("text1").Result) = True Then
intOne = ActiveDocument.FormFields("text1").Result
Else
intOne = 0
End If

If IsNumeric(ActiveDocument.FormFields("text2").Result) = True Then
intTwo = ActiveDocument.FormFields("text2").Result
Else
intTwo = 0
End If

If IsNumeric(ActiveDocument.FormFields("text3").Result) = True Then
intThree = ActiveDocument.FormFields("text3").Result
Else
intThree = 0
End If

Total = intOne + intTwo + intThree

MsgBox Total

End Sub
 
G

Greg Maxey

Try removing your Dim statements for your equation varialbls like:

Sub SumFormFields()
Dim oForm As Document
Dim Total As Double

Set oForm = ActiveDocument
Val1 = Val(oForm.FormFields("Text1").Result)
Val2 = Val(oForm.FormFields("Text2").Result)
Val3 = Val(oForm.FormFields("Text3").Result)

Total = Val1 + Val2 + Val3
MsgBox Total

End Sub

I am not smart enough to explain to you why this resolves the issue.
Perhaps one of the VBA Senseis will be along to enlighten us both.






How about:
 
S

Sabaka

Hi Greg,

I believe the reason that omitting DIM resolves the issue is because when a
data type for a variable is not declared VBA needs to give every variable a
data type and so gives it the "Variant" data type. In jbc's code, he was
declaring the data type of his variables as "integer." I don't think VBA
liked trying to assign a blank field to an integer.
 
G

Greg Maxey

Sabaka,

That was my thought as well. However, when I declared a blank variable as
Variant the macro still wouldn't play. There is something going on under
the hood that I still don't understand.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top