簡體   English   中英

Worksheet.Unprotect-Office Interop-2003和2007之間的區別

[英]Worksheet.Unprotect - Office Interop - Difference between 2003 and 2007

我有一個.NET winforms應用程序,該應用程序可以自動執行Excel並檢查工作表密碼。 要求是能夠檢測到1)保護已關閉2)密碼已刪除(受保護但沒有密碼)3)密碼與數據庫中的正確密碼匹配

為了滿足第二個要求,程序將使用空字符串調用Worksheet.Unprotect命令,以捕獲錯誤。 如果預期錯誤,則進行第三次檢查。 如果沒有錯誤,則取消保護無需密碼即可工作==>密碼已刪除。

下面的代碼示例具有這些檢查。

該應用程序可以在Office 2003上很好地完成工作。此后,我將開發機更新到了Office 2007,並且不再像以前那樣工作了。 當我調用Worksheet.Unprotect時,Excel會提示您輸入密碼!

我需要知道如何在新版本的Excel中完成此操作,或者是否有引用舊PIA的方法。 無論我如何設置對Excel 11的引用,GAC中都將其替換為PIA for 12。

'return true if unprotect of worksheet does not generate an error
    'all other errors will bubble up
    'return false if specific error is "Password is invalid..."
    Try
        'detect unprotected or no password
        If oWorksheet.ProtectContents Then
            'try with no passsword and expect an error
            'if no error then raise exception
            Dim blnRaiseException As Boolean = True
            Try
                'oWorksheet.Unprotect(vbNullString)
                oWorksheet.Unprotect()
            Catch ex As Exception
                blnRaiseException = False
            End Try

            If blnRaiseException Then
                Throw New ExcelSheetNoPasswordException
            End If

            oWorksheet.Unprotect(strPwd)
            'no error so if we get here -- success
            fnCheckWorksheetPwd = True

            'leave as it was -- this may still cause workbook to think it is changed
            oWorksheet.Protect(strPwd)
        Else
            Throw New ExcelSheetNotProtectedException
        End If

    Catch COMex As System.Runtime.InteropServices.COMException
        'handle error code -2146827284 
        If COMex.ErrorCode = -2146827284 Then
            'this is the error we're looking for
        Else
            Throw
        End If
    Catch ex As Exception
        Throw
    End Try

使用Worksheet.ProtectionMode屬性確定工作表是否受保護(而不是try..catch嘗試),然后嘗試Unprotect(“”)嘗試用空白密碼取消保護工作表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM