So I have a Workbook_open
sub that creates Long
variables when workbook is opened:
Private Sub Workbook_open()
MsgBox ("Workbook opened")
Dim i As Long
i = 68
End Sub
How would I pass the i
value to a Worksheet_change
sub for a particular worksheet?
Dim i
inside a procedure scope makesi
a local variable; it's only accessible from within the procedure it's declared in.The idea of passing
i
to another procedure is very sound: it means you intend to keep variable scopes as tight as possible, and that's a very very good thing.But in this case it's too tight, because the parameters of an event handler are provided by the event source: you need to "promote" that local variable up one scope level.
And the next tightest scope level is module scope.
You can use the
Dim
keyword at module level, but for consistency's sake I'd recommend using the keywordPrivate
instead. So in the same module, declare your module-level variable:If you want to expose that variable's value beyond this module, you can expose an accessor for it:
Now the
Sheet1
module'sWorksheet_Change
handler can read it:But it can't write to it, because the property is "get-only". If everyone everywhere needs to be able to read/write to it, then you might as well make it a global variable, or expose a mutator for it:
For that, declare
i
as aPublic Variable
on aStandard Module
likeModule1
and then you can access the value ofi
inSheet Change Event
if it isinitialized
duringWorkbook Open Event
.On Standard Module:
On ThisWorkbook Module: