So I'm experimenting with closing windows/apps in a vba macro I'm writing. Numerous posts online suggest the use of FindWindow
from the windows api.
I'm starting out slow, I'm trying to close a notepad window from my macro. (its one of a few things I want but it seems the easiest) and I found a solution, I forget where it was posted, it was short and sweet.
Sub CheckNotepad()
Dim hwnd As Long
hwnd = FindWindow("Notepad", vbNullString)
If hwnd Then
MsgBox "Notepad is running, the window handle is " & hwnd
Else
MsgBox "Notepad is not running"
End If
End Sub
seems great, its the start of how to get the handle for the notepad window, and from there I could find code to close the window using that handle. But it doesn't work for me!
All of the examples I have found use the 2 arguments, I would say half of which use vbNullString
as the second, some of which use a string for the caption of a particular window. But none of it works for me.
The only thing that works is supplying a 0 for the second argument (I assume this is in place of vbNullString
) but if I try to use vbnullstring
, or an actual string, I get a type mismatch error. and if I try to use any other number then excel stops working. (the lovely "Program has stopped working" message appears.
So, can give me some advise as to why this happens? I could just use the 0, but I'm guessing my user will have other notepad windows open so I'd like to be able to supply an argument to find the specific notepad window. (its going to be a temp window, popped up during the macro and subsequently closed as I do not want it left open for them to see)
Thanks in advance
I think you forgot to declare the API. Try the following (in a Module)
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Sub CheckNotepad()
Dim hwnd As Long
hwnd = FindWindow("Notepad", "HOUSE.txt - Notepad")
If hwnd Then
MsgBox "Notepad is running, the window handle is " & hwnd
Else
MsgBox "Notepad is not running"
End If
End Sub
This will give you the handle for HOUSE.txt file opened in notepad.