如何解锁C#中的excel文件中受保护的vbaproject?

时间:2013-03-07 12:48:58

标签: c# excel-vba vba excel

有人可以告诉我如何解锁受保护的Excel文件的vba项目吗?

我试过下面的C#代码:

Exc.wbook = (Excel._Workbook)Exc.Workbooks.Open(FilePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true);
Exc.VBE.ActiveVBProject = Exc.wbook.VBProject;
Exc.Visible = true;
SendKeys.SendWait("%{F11}^r{TAB}~" + sPrd + "~~%{F11}"); 

这并没有解锁vbaproject。

我也试过这个C#代码......没有用。

Exc.wbook = (Excel._Workbook)Exc.Workbooks.Open(FilePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true);
Exc.VBE.ActiveVBProject = Exc.wbook.VBProject;
Exc.Visible = true;
Exc.Unprotect(sPrd );

我已经使用假代码来遵循我的补偿规则 请仔细查看并告诉我我的代码有什么问题。

1 个答案:

答案 0 :(得分:0)

不幸的是,VBA不会在其对象模型中公开VBProject密码。因此,实现目标的唯一方法是通过解决方法。

通常的方法是使用SendKeys来模拟用于输入项目密码的击键。但是,您应该知道,这种方法并不是特别可靠,我当然不希望冒险使用我正在分销或销售的产品,或者在任何可能影响金钱或声誉的地方投入生产!

以下是我在Ozgrid Forums上找到的代码示例(最初由Bill Manville编写):

VB:

'need reference To VBA Extensibility 
'need To make sure that the target project Is the active project 
Sub test() 
    UnprotectVBProject Workbooks("ABook.xls"), "password" 
End Sub 

Sub UnprotectVBProject(WB As Workbook, ByVal Password As String) 
' 
' Bill Manville, 29-Jan-2000 
' 
Dim VBP As VBProject, oWin As VBIDE.Window 
Dim wbActive As Workbook 
Dim i As Integer 

Set VBP = WB.VBProject 
Set wbActive = ActiveWorkbook 

If VBP.Protection <> vbext_pp_locked Then Exit Sub 

Application.ScreenUpdating = False 

' Close any code windows To ensure we hit the right project 
For Each oWin In VBP.VBE.Windows 
    If InStr(oWin.Caption, "(") > 0 Then oWin.Close 
Next oWin 

WB.Activate 
' now use lovely SendKeys To unprotect 
Application.OnKey "%{F11}" 
SendKeys "%{F11}%TE" & Password & "~~%{F11}", True 

If VBP.Protection = vbext_pp_locked Then 
    ' failed - maybe wrong password 
    SendKeys "%{F11}%TE", True 
End If 

' leave no evidence of the password 
Password = "" 
' go back To the previously active workbook 
wbActive.Activate 

End Sub 

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
Sub ProtectVBProject(WB As Workbook, ByVal Password As String) 

Dim VBP As VBProject, oWin As VBIDE.Window 
Dim wbActive As Workbook 
Dim i As Integer 

Set VBP = WB.VBProject 
Set wbActive = ActiveWorkbook 

' Close any code windows To ensure we hit the right project 
For Each oWin In VBP.VBE.Windows 
    If InStr(oWin.Caption, "(") > 0 Then oWin.Close 
Next oWin 

WB.Activate 
' now use lovely SendKeys To unprotect 
    Application.OnKey "%{F11}" 
    SendKeys "+{TAB}{RIGHT}%V{+}{TAB}" & Password & "{TAB}" & Password & "~" 
    Application.VBE.CommandBars(1).FindControl(Id:=2578, recursive:=True).Execute 
    WB.Save 
End Sub 

使用它需要您自担风险!

HTH