由外部应用程序打开的新工作簿导致macros停止
我在工作中使用一个应用程序来search我的公司数据库。 应用程序将search结果导出到“AppData \ Local \ Temp \”文件夹中的Excel文件中。 我需要这个excel文件为我的主要macros来工作。
通常我手动点击应用程序中的button进行search,然后我发现我可以使用Windows API来为我做这个macros。 然后我写这个macros:
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文件打开并成为活动工作簿,所以我的macros停止工作。
当search结果信息窗口出现时,我遇到了同样的问题,但后来我把sendmessage切换到post消息,问题解决了。 有没有办法使我的macros运行,并忽略由外部应用程序打开的Excel文件?
编辑:更改Call SendMessage(search_results_excel, WM_CLOSE, 0, ByVal 0&)
Call PostMessage(search_results_excel, WM_CLOSE, 0, ByVal 0&) ThisWorkbook.Activate
问题解决。
更改您的macros,使其不使用ActiveWorkbook
,而是使用ThisWorkbook
引用自己或Workbooks("book_name.xlsm")
来引用名为“book_name.xlsm”的工作簿。 这样,任何单元格或工作表引用都会引用正确的工作簿,而不pipe其他书籍是打开的还是活动的工作簿。