Findwindow在64位VBA7中不起作用

解锁密码保护的VBA项目中提供的代码工作在32位,但不是64位。 特别,

Ret = FindWindow(vbNullString, "VBAProject Password") 

总是返回0.我已经尝试过

 Ret = FindWindow("#32770", "VBAProject Password") Ret = FindWindow("XLMAIN", "VBAProject Password") 

没有用。 我也尝试了以下API:setforegroundwindow,bringwindowtotop,setfocus,getactivewindow,getwindowthreadprocessid。 仍然失败,所以我不认为这是一个焦点问题。 也许是时机? 我试过使用

 SetTimer 

但我是API的新手,所以不知道如何实现。

我打电话通过我的personal.xlsb中的workbookopen应用程序事件我想在打开任何工作簿时填写密码。

 Private Sub AppEvent_WorkbookOpen(ByVal wb As Excel.Workbook) If wb.VBProject.Protection <> 1 Then Exit Sub End If Call unlockvba(wb) End Sub 

编辑:我已经将我的声明设置为PtrSafe和LongPtr在适用情况下。

弄清楚了。 这个问题不是64位,这是一个时间/焦点问题。

 Sub unlockVBA(wb) If wb.name = "PERSONAL.XLSB" Then Exit Sub Application.VBE.MainWindow.Visible = True TimerID = SetTimer(0&, 0&, 500&, AddressOf TimerProc) Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute End Sub Public Sub TimerProc(ByVal hwnd As LongPtr, ByVal wMsg As LongPtr, ByVal idEvent As LongPtr, ByVal dwTime As LongPtr) On Error Resume Next KillTimer hwnd, TimerID MyPassword = "password" Ret = FindWindow(vbNullString, "VBAProject Password") ChildRet = FindWindowEx(Ret, ByVal 0&, "Edit", vbNullString) If ChildRet <> 0 Then Call SendMessage(ChildRet, WM_SETTEXT, False, ByVal MyPassword) DoEvents End If ChildRet = FindWindowEx(Ret, ByVal 0&, "Button", vbNullString) If ChildRet <> 0 Then 'MsgBox "Button's Window Found" '~~> Get the caption of the child window strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr(0)) GetWindowText ChildRet, strBuff, Len(strBuff) ButCap = strBuff '~~> Loop through all child windows Do While ChildRet <> 0 '~~> Check if the caption has the word "OK" If InStr(1, ButCap, "OK") Then '~~> If this is the button we are looking for then exit OpenRet = ChildRet Exit Do End If '~~> Get the handle of the next child window ChildRet = FindWindowEx(Ret, ChildRet, "Button", vbNullString) '~~> Get the caption of the child window strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr(0)) GetWindowText ChildRet, strBuff, Len(strBuff) ButCap = strBuff Loop If OpenRet <> 0 Then '~~> Click the OK Button SendMessage ChildRet, BM_CLICK, 0, vbNullString Else MsgBox "The Handle of OK Button was not found" End If Else MsgBox "Button's Window Not Found" End If