ImJP
ImJP

Reputation: 13

I am getting an error when declaring variables in VBA

I'm trying to declare two variables with the values of each one, but there is an error "Declaration expected" in the lines where I assing the values of c and e. Why is this happening ? Am I declaring the variables wrong?

   Dim c As Integer

   Dim e As Integer

   c = 0

   e = 0

Thanks a lot for your feedback

Upvotes: 0

Views: 817

Answers (2)

Variatus
Variatus

Reputation: 14383

You can declare the variables outside a procedure to give them module-wide scope but you can't assign a value to them outside a procedure. Therefore this is correct.

Dim c As Integer
Dim e As Integer

Sub MyProcedure()

   c = 0                 ' the value is zero by default
   e = 0
End Sub

and this is correct, too.

Sub MyProcedure()

   Dim c As Integer
   Dim e As Integer

   c = 0                 ' the value is zero by default
   e = 0
End Sub

In the latter case the variables cannot be used in other procedures in the same module without again being declared there locally.

Upvotes: 2

Gustav
Gustav

Reputation: 55856

Place the variables in a separate code module, and declare them as Public:

Public c As Integer
Public e As Integer

They will default to the value 0 (zero).

Now you can assign them values from any form or code module.

Upvotes: 0

Related Questions