views:

167

answers:

1

I need to access the VBA code of Office documents (Excel workbooks, but it's not relevant) through .Net / C#. I know how to do this, but this requires the Office user to have granted trusted access to the VBA project object model through the Office app.
This makes me uncomfortable, because there is a risk that the user leaves things set that way, which is not desirable, and because this requires the user to fire the Office app and change the settings if access has not been granted, which is not pleasant for the user.
I believe .Net code cannot change that setting automatically (which is good), but is there a way to ask the user if he/she wants to temporarily grant authorization? Or is there a way to give access to the VBE specifically to my application when it gets installed?
My assumption is that none of these are feasible, but I thought that if someone knew the answer, he/she would be on StackOverflow :)
As a bonus question, does anyone know how to programmatically check whether an Office app has granted access to the VBA project object model (without a try/catch that is...)?

+3  A: 

Sadly what you're requesting is possible by modifying the registry keys relating to security. You can set the registry key, perform the tasks that you require, then set the registry key back, as in the example below.

  Public Sub ModifyVBA()
    Set wsh = CreateObject("WScript.Shell")
    'key to modify
    keyName = "HKEY_LOCAL_MACHINE\Software\Microsoft\Office\" & _
        Application.Version & "\Excel\Security\AccessVBOM"
    'enable access
    wsh.RegWrite keyName, 1, "REG_DWORD"
    'read the vba project name
    Application.VBE.ActiveVBProject.VBComponents.Add (vbext_ct_ClassModule)
    'disable access
    wsh.RegDelete keyName
End Sub

(Disclaimer: I think I originally lifted this from another forum).

Chris Spicer
Chris, thank you for the answer, just knowing that it is feasible is already valuable. I am not familiar with the language you use, is this vbscript?
Mathias
Glad to be of help Mathias. The language is all VBA, but your making calls to the Windows Script Host. The script host is very useful for affecting the environment that your VBA is running in.The RegWrite command is documented here: http://msdn.microsoft.com/en-us/library/yfdfhz1b%28VS.85%29.aspx
Chris Spicer
One afterthought - I imagine that more modern operating systems are far more restrictive about programmatic access to the registry, e.g. Vista and Windows 7. Probably best to double check the behaviour on those operating systems.
Chris Spicer
Yeah, I checked it with Win7/Excel 2007 and it failed, but on XP/Excel 2003 it (partially) worked. I was ideally looking for C#/.Net code, but I'll take that, it's by far the best answer ;), and knowing that it is possible is very helpful.
Mathias