2010-03-05 72 views
1

我有一個.NET winforms應用程序,可以自動執行Excel並檢查工作表密碼。這個要求是能夠檢測 1)的保護功能被關閉 2)密碼被刪除(保護,但沒有密碼) 3)密碼正確的密碼從數據庫匹配Worksheet.Unprotect - Office Interop - 2003與2007之間的差異

爲了滿足第二個要求,程序使用空字符串調用Worksheet.Unprotect命令,捕獲錯誤。如果出現錯誤,則進行第三次檢查。如果沒有錯誤,那麼Unprotect在沒有密碼的情況下工作==>密碼已被刪除。

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

該應用程序可以在Office 2003中做到這一點。此後,我的開發計算機已更新到Office 2007,並且它不再像以前那樣工作。當我打電話給Worksheet.Unprotect時,Excel會提示輸入密碼!

我需要知道這應該如何在新版本的Excel中完成,或者如果有方法來引用舊的PIA。無論如何設置對Excel 11的引用,它都會在GAC中替換爲12的PIA。

'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 
+0

如果將Excel.Application實例的DisplayAlerts屬性設置爲False,會發生什麼情況? – 2010-03-05 16:35:32

回答

0

使用Worksheet.ProtectionMode屬性來確定如果工作表被保護(而不是在try..catch嘗試),並試圖撤消(「」)來嘗試使用空密碼不受保護的工作表。

相關問題