我在工作中使用应用程序来搜索我的公司数据库。应用程序将搜索结果导出到“AppData \ Local \ Temp \”文件夹中的excel文件。我需要这个excel文件供我的主宏工作。
通常我手动点击应用程序中的按钮进行搜索,然后我发现我可以使用windows api为我做一个宏来做这个。然后我写这个宏:
Public Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function FindWindowEx Lib "user32.dll" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Public Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByRef lParam As Any) As Long
Public Declare Function PostMessage Lib "user32.dll" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Const WM_CLOSE As Long = &H10
Public Const BM_CLICK As Long = &HF5&
Sub Makro1()
advanced_search = FindWindow("WindowsForms10.Window.8.app.0.33c0d9d", vbNullString)
window_group_1 = FindWindowEx(advanced_search, 0&, "WindowsForms10.Window.8.app.0.33c0d9d", vbNullString)
window_group_2 = FindWindowEx(advanced_search, window_group_1, "WindowsForms10.Window.8.app.0.33c0d9d", vbNullString)
search_button = FindWindowEx(window_group_2, 0&, "WindowsForms10.BUTTON.app.0.33c0d9d", "Search")
excel_button = FindWindowEx(window_group_2, 0&, "WindowsForms10.BUTTON.app.0.33c0d9d", "Export to Excel")
Call PostMessage(search_button, BM_CLICK, 0, 0)
Do
DoEvents
search_results_info = FindWindow("WindowsForms10.Window.8.app.0.33c0d9d", "Search Results")
Loop Until search_results_info > 0
search_results_info_button = FindWindowEx(search_results_info, 0&, "WindowsForms10.BUTTON.app.0.33c0d9d", vbNullString)
Call PostMessage(search_results_info_button, BM_CLICK, 0, 0)
Call PostMessage(excel_button, BM_CLICK, 0, 0)
Do
DoEvents
search_results_excel = FindWindow("XLMAIN", "Microsoft Excel - search_results")
Loop Until search_results_excel > 0
Call SendMessage(search_results_excel, WM_CLOSE, 0, ByVal 0&)
End Sub
代码将一直运行,直到执行以下行。
Call PostMessage(excel_button, BM_CLICK, 0, 0)
在此行之后,temp文件夹中的excel文件打开并变为活动工作簿,因此我的宏停止工作。
我在搜索结果信息窗口出现时遇到了同样的问题,但后来我将sendmessage切换为发布消息,问题解决了。 是否有任何方法可以让我的宏运行并忽略外部应用程序打开的excel文件?
编辑:已更改
Call SendMessage(search_results_excel, WM_CLOSE, 0, ByVal 0&)
至
Call PostMessage(search_results_excel, WM_CLOSE, 0, ByVal 0&)
ThisWorkbook.Activate
问题已解决。
答案 0 :(得分:1)
更改您的宏,使其不使用ActiveWorkbook
,而是使用ThisWorkbook
引用自身或Workbooks("book_name.xlsm")
引用名为“book_name.xlsm”的工作簿。这样,任何单元格或工作表引用始终引用正确的工作簿,无论其他书籍是打开的还是活动工作簿。