Basics of VBA / Macros Chapter – 6 (Declaring Variables Part-4)

⏱ 2 min read

Static Variables

Sometimes you want to retain the value of a variable in VBA when a procedure ends. You can achieve this by using the Static keyword.

Dim Statement in Excel VBA

Advertisement

Result when you click the command button on the sheet:

Dim Statement Result

Result when you click another time:

Dim Statement Result

VBA destroys the variable when the procedure ends. Each time you click the command button on the sheet. VBA creates the variable x again, adds the value 1 to it and displays the result.

Now replace the keyword Dim with the keyword Static.

Static Keyword in Excel VBA

Result when you click the command button on the sheet:

Static Keyword Result

Result when you click another time:

Static Keyword Result

Static variables retain their values, even when a procedure ends. Static variables will be destroyed when you click the Reset/Stop button or when you close your workbook.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong