Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vba - Remove protected view from Excel sheet opened programmatically in Access

I have a spreadsheet I open programmatically using the VBA in Access:

Set xl = CreateObject("Excel.Application")
With xl
    Call RunASCFormatting(xl, wb, strPath)
    'More code

Sub RunASCFormatting(xl As Excel.Application, wb As Excel.Workbook, strPath As String)
    With xl
        If .ProtectedViewWindows.count > 0 Then
            .ActiveProtectedViewWindow.Edit
        End If
        Set wb = .Workbooks.Open(Trim(strPath) & "ASC.xls", True, False)
        wb.Sheets(1).Rows("1:1").Delete Shift:=xlUp
        .ActiveWorkbook.SaveAs FileName:=Trim(strPath) & "ASC.xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    End With
End Sub

I have added in the "If" statement in the sub as I was hoping it would remove the "Protected View - Editing this file type is not recommended due to your File Block settings in the Trust Center" message. What I'm trying to achieve is to get the "Enable Editing" button removed, so this macro can enable editing and run as planned.

Currently, the code falls at the "Set wb" line. What is the proper way to achieve what I'm after?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One possibility is to change the macro security settings programmatically to the lowest before you open the Excel workbook. After manipulating your data, re-enable the previous setting of the macro security.

Here's some revised code which I found at http://www.mrexcel.com/forum/excel-questions/631545-change-trust-center-settings-visual-basic-applications.html:

Public Sub MySubroutine()
    Dim lSecurity As Long

    lSecurity = Application.AutomationSecurity
    Application.AutomationSecurity = msoAutomationSecurityLow

    '''''''''''''''''''''
    '   Run code here   '
    '''''''''''''''''''''

    Application.AutomationSecurity = lSecurity
End Sub

As a side comment, VBA implements Integer as Long, so it could actually be slightly more performance degrading to declare Integer variables as it has to reinterpret the Integer keyword. When I learned that, I started declaring an Integer as Long instead. I actually read this in some Microsoft documentation, but I lost the link to it years ago.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...