Initializing a global variable

samsung180

New Member
Joined
Nov 14, 2011
Messages
2
I would like to set a variable (let's call it var) as having an initial value of 0.
I would like this to be set outside of a function so that when I run a function, var does not have its value always reset to 0.
For example, here is something similar to what I'd like:

Dim var As Integer
var = 0

Public Function justAnExample ()
var = var + 1
End Function

Any help? Thanks.
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
Welcome to the forums!

Try declaring the variable in this manner:

Code:
[B]Public Const var As Integer = 0[/B]

Sub Foo()
MsgBox var + 1
End Sub
 
Upvote 0
Have you considered something like

Code:
Function JustAnExample2(Optional Reset as Boolean = True)
    Static myValue as Long

    If Reset Then
        myValue = 0
    Else
        myValue = myValue +1
    End If

    JustAnExample2 = myValue
End Function
 
Upvote 0
Basically, I just want a variable to start at 0, then for each iteration of my function, have its value increased by 1 (thus why a constant will not work here).

Maybe this will work:

Code:
Sub varDeclaration ()
var = 0
End Sub
 
Upvote 0
=JustAnExample2(FALSE) will act that way.

Try putting this formula in a cell. It will re-calcualte any time that A1 is changed

=JustAnExample2(A1<>A1)
 
Upvote 0

Forum statistics

Threads
1,214,956
Messages
6,122,465
Members
449,085
Latest member
ExcelError

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top