龙空技术网

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

office大咖 939

前言:

当前咱们对“vb查找文件是否存在”可能比较看重,姐妹们都需要剖析一些“vb查找文件是否存在”的相关资讯。那么小编同时在网上网罗了一些对于“vb查找文件是否存在””的相关内容,希望你们能喜欢,小伙伴们快快来了解一下吧!

在EH论坛看到这样的一个例子:

需要判断文本是否处于打开状态,如果处于打开状态,则关闭该文件

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

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

#If Win64 ThenPrivate Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPrivate 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#ElsePrivate Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPrivate 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 IfConst WM_CLOSE = &H10Sub 判断txt文件是否打开并关闭()Dim hWnd As Long, S As String, myFileName As StringmyFileName = "F:\a.txt"S = Mid(myFileName, InStrRev(myFileName, "\") + 1, Len(myFileName)) & " - 记事本"hWnd = FindWindow(vbNullString, S)If hWnd > 0 ThenMsgBox "文件已打开"PostMessage hWnd, WM_CLOSE, 0&, 0&ElseMsgBox "未发现文本文件:" & SEnd IfEnd Sub

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

`

Sub ps()Dim S As String, myFileName As StringmyFileName = "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, TrueIf Dir(toFileName) <> "" ThenMsgBox "文件已打开"ElseMsgBox "未发现文本文件:" & SEnd IfEnd Sub

思路也差不多,通过Get-Process 找出窗体标题,如果有,则创建临时文件,并关闭进程。

通过判断临时文件的是否存在,来判断文件是否已打开。

标签: #vb查找文件是否存在 #vb如何判断文件是否存在 #vba中判断文件是否存在