2017-06-28 49 views
0

我一直在嘗試如何知道哪些訪問我的excel文件。 在某些情況下,例如,如果您打開一個word文件「winword.doc」 它將創建〜$ winword.doc文件,其中如果您在記事本中打開它將顯示當前用戶。然而這並不適用於所有人。如何知道用戶訪問我的excel文件在vb.net

我想知道如何在vb.net或vb代碼中檢查excel文件的用戶。

Private Function CheckFile(ByVal filename As String) As Boolean 
    Try 
     'Check file access if can be opened 
     System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None).Close() 
     'Return CheckFile to False if File is not opened 
     Return False 
     Catch ex As Exception 
     'If file deemed to be open Boolean is True 
     Return True 
    End Try 
End Function 
Private Function CheckIfRunning(ByVal processname As String) As Boolean 
    'processname = "SLDWORKS" 
    Dim CurrentSessionID As Integer = Process.GetCurrentProcess.SessionId 
    Dim val As String = "no" 
    For Each proc As Process In Process.GetProcesses 
     If proc.SessionId = CurrentSessionID Then 
      val = "yes" 
     End If 
    Next 
    If val = "no" Then 
     Return False 
    Else 
     Return True 
    End If 
End Function 
Public Sub Main() 
    Dim freader As System.IO.StreamReader 
    'Loop while file still opened 
    Do While CheckFile("location.xls") = True 
     If CheckIfRunning("EXCEL.EXE") = True Then 
     Else 
      MsgBox("file is not running in process. File Must be opened in another location") 
     End If 
     Threading.Thread.Sleep(5000) 
    Loop 
    End Sub 

希望你能幫助我。我想知道誰訪問我的文件以及誰鎖定了它。 這有一個缺陷,如果你在你的站打開Excel文件,它將始終返回false。

回答

0

This answer適合我,無論是在本地還是通過不同用戶的網絡。我正在使用Excel 2013.

我認爲RoryA在012上是Rory,所以如果他出現了,我會刪除我的答案而贊成他,這樣他就可以得到他應得的選票。

請注意,這是VBA代碼。如果/如何轉化爲其他VB範圍,我不知道。

Public Function WhoHasXMLWorkbookOpen(strFile As String) As String 
    Dim vFileParts 

    vFileParts = VBA.Split(strFile, "\") 
    vFileParts(UBound(vFileParts)) = "~$" & vFileParts(UBound(vFileParts)) 
    strFile = VBA.Join(vFileParts, "\") 

    If CreateObject("Scripting.FileSystemObject").FileExists(strFile) Then 
     WhoHasXMLWorkbookOpen = GetFileOwner(strFile) 
    End If 
End Function 

Public Function GetFileOwner(ByRef strFileName As String) As String 
'http://www.vbsedit.com/scripts/security/ownership/scr_1386.asp 
    Dim objFileSecuritySettings  As Object 
    Dim objSD      As Object 
    Dim intRetVal     As Integer 

    Set objFileSecuritySettings = _ 
    GetObject("winmgmts:").Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'") 
    intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD) 

    If intRetVal = 0 Then 
     GetFileOwner = objSD.Owner.Name 
    Else 
     GetFileOwner = "Unknown" 
    End If 
End Function 

實例:

? WhoHasXMLWorkbookOpen("X:\Directory\file.xlsm") 
相關問題