1

有人可以告诉我如何解锁受保护的 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 );

我放了假代码来遵循我的比较规则。
请查看它并告诉我我的代码有什么问题。

4

1 回答 1

0

不幸的是,VBA 没有在其对象模型中公开 VBProject 密码。因此,实现您想要的唯一方法是通过解决方法。

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

这是我在Ozgrid 论坛上找到的代码示例(最初由 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 

需要您自担风险使用它!

高温高压

于 2013-03-07T13:05:08.427 回答