判斷excel檔案是否被開啟

pb8發表於2010-01-02

    Private Declare Function lOpen()Function lOpen Lib "kernel32" Alias "_lopen" (ByVal lpPathName As String, ByVal iReadWrite As Long) As Long
    Private Declare Function lClose()Function lClose Lib "kernel32" Alias "_lclose" (ByVal hFile As Long) As Long

    '       判斷某檔案是否在使用中      
    Public Function IsFileAlreadyOpen()Function IsFileAlreadyOpen(ByVal FileName As String) As Boolean
        Dim hFile As Long
        Dim lastErr As Long
        hFile = -1                                                                                  '       初始化檔案控制程式碼.      
        lastErr = 0
        hFile = lOpen(FileName, &H10)

        If hFile = -1 Then                                                                       '       檔案是否能正確開啟並可共享      
            lastErr = Err.LastDllError
        Else
            lClose(hFile)
        End If
        IsFileAlreadyOpen = (hFile = -1) And (lastErr = 32)
    End Function

    Private Sub Command1_Click()Sub Command1_Click()
        Dim strFileName As String
        strFileName = "d:/050304_chengji.xls"                   '       你的檔案      
        If IsFileAlreadyOpen(strFileName) Then
            MsgBox("指定檔案已開啟")
        Else
            MsgBox("指定檔案未開啟")
        End If
    End Sub

相關文章