PDA

View Full Version : [SOLVED:] Baffling Scope Issue



gmaxey
12-15-2013, 12:21 PM
I'm stumped by the behavior of a module level variable. It works fine is the template, but when I create new documents from the template, the variable is for some reason falling out of scope.

Simple to duplicate. Create a new template. In the ThisDocument module of the template, paste the following code:


Option Explicit
Private m_oCCTest As ContentControl
Private Sub Document_ContentControlOnEnter(ByVal oCC_Entered As ContentControl)
'Set the module level CC variable to the CC entered.
Set m_oCCTest = oCC_Entered
If Not m_oCCTest Is Nothing Then
MsgBox "A CC was entered and the variable m_oCCTest is set"
End If
Application.OnTime Now + TimeSerial(0, 0, 0.1), "CCRunTest"
lbl_Exit:
Exit Sub


End Sub
Public Sub CCRunTest()
On Error Resume Next
MsgBox "Running test. The Test CC text is: " & m_oCCTest.Range.Text
If Err.Number <> 0 Then
MsgBox "m_oCCTest is out of scope. Why?"
End If
End Sub


Add a few content controls, observe the message boxes while changing the text. No problems.

Now save and close the template and create a new document from it.

For some reason the module level variable is being set, but it is now out of scope in the CCRunTest procedure?

Can anyone explain why? Thanks

Paul_Hossler
12-15-2013, 02:22 PM
I think it's the OnTime launch of another process, with the 'holding CC' variable being scoped to the ThisDocument class object


Put this into a Standard Module and it seems to work



Public m_oCCTest As ContentControl


Paul

(The .zip extension is to fake out the system. It's really a normal dotm)

gmaxey
12-15-2013, 04:28 PM
Paul,

Yes that works! Thanks.

Still baffling though ;-)

Paul_Hossler
12-16-2013, 08:24 AM
http://word.mvps.org/


"Word rarely misses an opportunity to perplex"

Bob Buckland


Truer words were never spoken

Paul

Frosty
12-17-2013, 01:32 PM
FYI - I don't have this problem in Word 2010... it runs fine. I know you and I have worked on content controls in Word 2007 before, and how some of the events double-fire or don't fire...Technically, I think this is a variable "lifetime" issue, rather than a variable "scope" issue. I wondered if it had something to do with ByVal, but your sample code worked just fine in my Word 2010 instance.

Frosty
12-17-2013, 01:33 PM
That said, to find out when the variable falls out of memory... set a Watch to that variable, and break when the value changes -- the execution should stop when the variable gets populated, and stop again when it becomes nothing.

gmaxey
12-17-2013, 04:14 PM
Jason,

Thanks for your input and for looking at the file offline. In this case, I think Paul (or Bob Buckland) is right.