Avatar of Jos te Braake
Jos te Braake
Flag for South Africa asked on

Variable read before written

I often use the following construct in my VBA code to track the progress of my code execution:

Public Sub Cmd3HideUnhide(sWksName As String, sHideUnhide As String)
   On Error GoTo ErrHandler
   Dim sProcNameCmd3 As String
   sProcNameCmd3 = sWksName & ".HideUnhide.CmdBtn3HideUnhide"

other code
ErrHandler:
       Call DspErrMsg(sProcNameCmd3)
End sub

When I run Project Analyzer it registers an error with the comment:

Variable read before written (along some path): sProcNameCmd3          in HideUnhide.Cmd3HideUnhide     Type: Logic

As I have declared the variable sProcNameCmd3, assigned a value to this variable and later in the same procedure use that variable in a procedure call, I do not understand why this is referred to as "Variable read before written". Surely assigning a value to a variable constitutes writing the variable?
I also do not understand what I should do to rectify the problem.

I shall be grateful to assistance in this matter.
VBA

Avatar of undefined
Last Comment
Jos te Braake

8/22/2022 - Mon
Bill Prew

My guess would be that because it's used in the error handling routine, in theory it could be referenced anytime after the ON ERROR, which could be during or before the statement where you set its initial value.

Does this give the same error?

Public Sub Cmd3HideUnhide(sWksName As String, sHideUnhide As String)
   Dim sProcNameCmd3 As String
   sProcNameCmd3 = sWksName & ".HideUnhide.CmdBtn3HideUnhide"
   On Error GoTo ErrHandler

other code
ErrHandler:
       Call DspErrMsg(sProcNameCmd3)
End sub

Open in new window

Martin Liss

I don't see any problem if procedure DspErrMsg exits. BTW you don't need the "Call" and DspErrMsg sProcNameCmd3 should be enough.
Jos te Braake

ASKER
Bill, your suggestion solves the problem. By placing
On Error GoTo ErrHandler
after the declaration and assignment of a value to the variable the error does not come up.
I assume this option means that if an error occurs before the On Error statement that the execution will not be handled by the ErrHandler.

I also tried declaring the variable as a public variable at the module level. That also solved the problem.

Can anyone throw any light on why these changes solve the problem?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER CERTIFIED SOLUTION
Bill Prew

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jos te Braake

ASKER
Thanks Bill. That solves my problem and gives me the understanding I was looking for.