Declaring variables in a loop

R

RD

Hi all,

I've written some code that parses data out of Word forms and writes records to
an Oracle db. The amount of code is large because there are a lot of fields and
quite a bit of logic behind which fields are extracted and which table they are
written to.

When I first wrote the code I was declaring variables right before I needed
them. This was before we started looping through numerous files on the network
drive. Even now, I might go through a large percentage of the files in the
folder before finding one suitable to be parsed out. My thinking here was why
declare any variable until you need them? So, now I have a bunch of variables
declared within my loop.

I guess my question is, am I screwing myself by declaring variables in a loop?
Should I move all my variable declarations out of the loop?

Thoughts and insights appreciated,
RD
 
B

Brendan Reynolds

As I understand it, variable declarations are processed when the code is
compiled, not when it is executed, so from that point of view it probably
makes no difference where you declare them. Most VB/VBA programmers declare
their variables together at the start of a procedure, so that they know
where to find them. I'd be inclined to stick with that convention unless you
have a good reason not to - and I really can't think of one. (At least, not
in the context of VBA or 'classic' VB. The situation is, I believe, somewhat
different in .NET.)
 
C

Corey-g via AccessMonster.com

I have to agree, you should declare all of your variable at the top of your
procedure (if they are used in the procedure) and set them when / where you
need (and comment what it's for and why).

What happens is that you finish this app, then come back 6 months / a year
later to fix something that broke due to a patch / environment changes / etc..
.., and you have forgotten how / why you did things. then you spend a huge
amount of time trying to troubleshoot...

Just my 2 cents...

Corey
 

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