我有一个.NET winforms应用程序可以自动化Excel并检查工作表密码。要求是能够检测到 1)保护功能已关闭 2)密码被删除(受保护,但没有密码) 3)密码与数据库中的正确密码相匹配
为了满足第二个要求,程序使用空字符串调用Worksheet.Unprotect命令,捕获错误。如果错误如预期,则进行第3次检查。如果没有错误,那么Unprotect在没有密码的情况下工作==>密码已删除。
下面的代码示例包含这些检查。
应用程序可以使用Office 2003做到这一点。我已经将我的开发机器更新到Office 2007,它不再像以前一样工作。当我调用Worksheet.Unprotect时,Excel会提示输入密码!
我需要知道如何在新版本的Excel中完成此操作,或者是否有方法可以引用旧的PIA。无论如何设置对Excel 11的引用,它都将替换为GAC中的12 for 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 :(得分:0)
使用Worksheet.ProtectionMode属性确定工作表是否受保护(而不是try..catch尝试),并尝试取消保护(“”)以尝试使用空白密码取消保护工作表。