2

I believe I read somewhere that in VBA, if you Dim a variable in a function or a module, it doesn't matter whether it's at the top or anywhere else in the module or function. I read that the compiler will scan for the Dim statements when it enters a Function or Module and allocates the memory, and then jump back to the top and start executing code.

I also believe it is personal preference for programmers in VBA to either Dim at the top or Dim as they go, I prefer the second option. My question is whether there is any official documentation on exactly how the compiler handles the Dim statements or if it can be demonstrated that the above assertion is true.

I would love to read in detail on how the compiler handles the Dim statements as to when it allocates memory, i.e., before executing the code or as it comes across the dim statements. Can that be demonstrated?

this
  • 1,406
  • 11
  • 23
Name
  • 209
  • 1
  • 4
  • 2
    `Dim` statements aren't executed. My personal preference is to `Dim` the variable close to where it's used. Helps in refactoring. As to documentation, that is a good question, not sure. – BigBen Jul 30 '20 at 16:42
  • Unfortunately asking for documentation is off topic here, and as such this will most likely be closed. – Scott Craner Jul 30 '20 at 16:48
  • [This question](https://stackoverflow.com/questions/36751682/when-are-vba-variables-instantiated) should be helpful. – BigBen Jul 30 '20 at 17:06
  • 1
    https://learn.microsoft.com/en-us/office/vba/language/concepts/getting-started/understanding-the-lifetime-of-variables looks like the updated URL for the documentation. – BigBen Jul 30 '20 at 17:18
  • @ScottCraner, where is asking for Documentation allowed? – Name Jul 30 '20 at 18:13
  • Looks like @BigBen gave you the documentation. But other than that I do not know. I only frequent this site and SuperUser. Neither allow that type of question. – Scott Craner Jul 30 '20 at 18:19
  • 2
    @ScottCraner Asking for specific official documentation is allowed here, as per [When is a resource request on-topic?](https://meta.stackoverflow.com/a/386006/7296893). This question seems valid, I've cast a reopen vote. – Erik A Aug 19 '20 at 10:40

0 Answers0