定义一个excel VBA function 如果B2位置显示的文件已经打开则显示OK否则则显示 file not opened
您可以使用以下VBA代码来定义一个函数,以检查指定单元格中的文件是否已经打开:
Function CheckFileOpened(rng As Range) As String
Dim fileName As String
' 获取文件名
fileName = rng.Value
' 检查文件是否已经打开
If IsFileOpened(fileName) Then
CheckFileOpened = "OK"
Else
CheckFileOpened = "File not opened"
End If
End Function
Function IsFileOpened(fileName As String) As Boolean
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open fileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
' 如果文件已经打开,ErrNo 的值将不为 0
IsFileOpened = ErrNo <> 0
End Function
然后,您可以在Excel中的B2单元格中使用该自定义函数来检查文件是否已经打开。例如,将以下公式输入到B2单元格中:
=CheckFileOpened(B2)
如果B2位置显示的文件已经打开,则B2单元格将显示"OK";否则,B2单元格将显示"File not opened"
原文地址: http://www.cveoy.top/t/topic/iXWc 著作权归作者所有。请勿转载和采集!