I have set up a timer in an Office addin (being developed in VB.net) that I can set going fine, using the code:
Public Class ThisAddIn
Friend WithEvents Timer1 As System.Timers.Timer
Private Sub ThisAddIn_Startup() Handles Me.Startup
Me.Timer1 = New System.Timers.Timer()
Me.Timer1.Interval = 500
Me.Timer1.Enabled = True
End Sub
Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed
Me.Timer1.Enabled = False
MsgBox("Code Ran!")
End Sub
I would like to call this timer when a user changes a setting in the addin’s ribbon, but I cannot seem to access the event. If I use the code:
Public Class ServerRibbon
Public myCaller As ThisAddIn
private sub respondToClick()
Dim blah As System.Timers.Timer
blah = myCaller.Timer1
blah.Enabled = True
end sub
I get an error of ‘object reference not set to an instance of an object’. Can anyone explain how I can set the timer going?
Thanks in advance,
Your code doesn’t work because
myCalleris not set to your particular instance ofThisAddIn(theoretically, there could be manyThisAddIninstances floating around your memory).However, since you are developing an office add-in, there is in fact only a single instance of ThisAddIn. A simple workaround to get access to the timer would be to make Timer1 a shared variable:
This would allow you to access the timer as
ThisAddIn.Timer1.(Note that, in general, publicly accessible shared fields (aka global variables) are a bad idea. However, in your case, it might just be the simplest solution that allows you to do what you want.)
PS: You might want to read up on the difference between a class and an instance of a class.
EDIT: Since you have an event handler attached to the timer, you either
(a) need to make the event handler shared as well (
Private Shared Sub Timer1_Elapsed...), which has the disadvantage that your event handler cannot access instance variables of ThisAddIn anymore, or(b) Make the instance of
ThisAddInaccessible through a separate property instead of making the field shared: