How to close notepad with file system object using VBA - Stack Overflow

admin2025-04-26  2

im trying to open and close a notepad using vba, the following code works to open, but no idea how to close it, I already tried fso.close and fso.quit but error raise, do you know how to achieve this??

Dim fso As Object
Dim sfile As String
Set fso = CreateObject("shell.application")
sfile = "C:\Users\Universal\Desktop\test.txt"
fso.Open (sfile)

im trying to open and close a notepad using vba, the following code works to open, but no idea how to close it, I already tried fso.close and fso.quit but error raise, do you know how to achieve this??

Dim fso As Object
Dim sfile As String
Set fso = CreateObject("shell.application")
sfile = "C:\Users\Universal\Desktop\test.txt"
fso.Open (sfile)
Share Improve this question asked Jan 13 at 16:41 KrenskKrensk 11 bronze badge 4
  • 1 What's the purpose of the open/close? – Tim Williams Commented Jan 13 at 16:43
  • What error is raised? – CHill60 Commented Jan 13 at 16:47
  • stackoverflow.com/questions/26303173/… – Tim Williams Commented Jan 13 at 16:48
  • 1 If you would run the code on my computer, it would open Notepad++ (because that's my default for txt-files). If you now try to close Notepad, this would either fail or it would close a random Notepad instance that I have open by coincidence. If you would close close Notepad++, I would be mad because I have lots of files open. That said: Why do you want to open a textfile but also later (when?) close it via code? – FunThomas Commented Jan 13 at 17:20
Add a comment  | 

1 Answer 1

Reset to default 0

You can try with this simple code. If can be done in different way if I know the purpose.

Sub QuitNotepad()
    On Error Resume Next
    'taskkil to terminate process; switch /F forces termination process
    'vbHide-> to run command without showing process name
    Shell "taskkill /F /IM notepad.exe", vbHide
    On Error GoTo 0
End Sub


Sub OpenNotepad()
  Dim MyFile As String
  MyFile = "d:\aaa.txt"
  Shell ("C:\Windows\system32\notepad.exe" & " " & MyFile), vbNormalFocus
End Sub

转载请注明原文地址:http://anycun.com/QandA/1745636770a91036.html