VBA学堂——判断文件是否打开

在EH论坛看到这样的一个例子:
需要判断文本是否处于打开状态,如果处于打开状态,则关闭该文件

帖子给出了解决的思路:已知txt文件名,可以根据文件名遍历窗体判断是否打开

下面的代码用API函数来解决,通过 FindWindow找出窗体的标题,用PostMessage来关闭进程

#If Win64 Then
    Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Private Declare PtrSafe Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
#Else
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
#End If
Const WM_CLOSE = &H10

Sub 判断txt文件是否打开并关闭()
    Dim hWnd As Long, S As String, myFileName As String
    myFileName = "F:\a.txt"
    S = Mid(myFileName, InStrRev(myFileName, "\") + 1, Len(myFileName)) & " - 记事本"
    hWnd = FindWindow(vbNullString, S)
    If hWnd > 0 Then
        MsgBox "文件已打开"
        PostMessage hWnd, WM_CLOSE, 0&, 0&
    Else
        MsgBox "未发现文本文件:" & S
    End If
End Sub

下面,我提供另外一种解决的思路,用Powershell来判断并关闭进程。

Sub ps()
    Dim S As String, myFileName As String
    myFileName = "F:\a.txt"
    toFileName = "F:\a.ini"
    S = Mid(myFileName, InStrRev(myFileName, "\") + 1, Len(myFileName)) & " - 记事本"

    pc = "Remove-Item -Recurse '" & toFileName & "'" & vbCrLf & _
        "Get-Process |foreach-object {if( $_.mainWindowTItle -eq '" & S & "') { $_.Kill() |Out-File '" & toFileName & "'}}"

    CreateObject("WScript.Shell").Run "powershell " & pc, 0, True
    If Dir(toFileName) <> "" Then
        MsgBox "文件已打开"
    Else
        MsgBox "未发现文本文件:" & S
    End If
End Sub

思路也差不多,通过Get-Process 找出窗体标题,如果有,则创建临时文件,并关闭进程。
通过判断临时文件的是否存在,来判断文件是否已打开。

案例下载:
https://pan.baidu.com/s/1thYcjwP6iSgPGIxhivyZdQ

你可能感兴趣的:(VBA学堂——判断文件是否打开)