How to check from .net code whether “Trust access to the VBA project object model” is enabled or not for an Excel application?

后端 未结 4 1164
情深已故
情深已故 2020-12-16 00:47

How to check from .net code whether \"Trust access to the VBA project object model\" is enabled or not for an Excel application?

Manually I

相关标签:
4条回答
  • 2020-12-16 00:51

    The short answer is that you cannot directly access this setting using the Excel object model (i.e. through PIAs). However, instead, you can check this setting from the registry in the following location (here I assume that you're using Office 2007 - version 12.0):

    HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security\AccessVBOM
    

    this is a DWORD that will be 0 or 1 depending on whether the "Trust access to VBA Object Model" is enabled.

    However, this setting can be overriden by another registry key located at:

    HKEY_LOCAL_MACHINE\Software\Microsoft\Office\12.0\Excel\Security\AccessVBOM
    

    this is again a DWORD, however, if this value is 0 this means that no matter what the HKCU value is set to, then access to the VBOM will be denied. If the value in HKLM is 1 or missing, then the HKCU key will control the access to the VBOM.

    Therefore, all you need to do is to check these two keys via the Registry methods in .NET.

    0 讨论(0)
  • 2020-12-16 00:52

    Search the registry for all instances of "AccessVBOM" and change the Dword settings to a 1.

    That should turn it on.

    0 讨论(0)
  • 2020-12-16 01:02

    This worked for me

    Function VBATrusted() As Boolean
        On Error Resume Next
        VBATrusted = (Application.VBE.VBProjects.Count) > 0
    End Function
    
    Private Sub Workbook_Open()
        If Not VBATrusted() Then
        MsgBox "No Access to VB Project" & vbLf & _
          "Please allow access in Trusted Sources" & vbLf & _
          "File > Options > Trust Center > Trust Center Settings > Macro Settings > Trust Access..."
        End If
    End Sub
    

    Source https://www.mrexcel.com/forum/excel-questions/659774-checking-if-trust-access-visual-basic-project-ticked.html

    0 讨论(0)
  • 2020-12-16 01:10

    It has been my experience that Application.VBE will (depending on OFFICE version) either be *null* or throw a COMException whenever the VBA Project Object Model is not trusted.

    If one is using Office.Interop in an Add-In then Globals.ThisAddIn.Application.VBE will perform the necessary test.

    I have used this proxy for years successfully.

    0 讨论(0)
提交回复
热议问题