swApp is null

In many of the examples I see in the SW api, the following line is used:

mDoc2 = (ModelDoc2)swApp.ActiveDoc;

However, in some code I'm working on I always get a failure here because swApp is null.

In the examples I have seen (c#), swApp is never set to anything, so how can this variable be used?

I'm assuming that the examples I've seen are standalone as opposed to addins. The code I'm working on

is part of an addin so I could pull the SW application from the "connectToSW" function and pass it to

this other piece of code, but how would this variable be set otherwise?

I have attached the file in question if that helps.

Thanks for any pointers

SolidworksApi macros