如何知道用户在vb.net中访问我的excel文件

时间:2017-06-28 08:02:46

标签: vb.net vba excel-vba vbscript excel

我一直在尝试知道哪些是访问我的Excel文件。 在某些情况下,例如,如果你打开一个word文件" winword.doc" 它将创建〜$ winword.doc文件,如果在记事本中打开它将显示当前用户。但这不适用于所有人。

我想知道如何在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。

1 个答案:

答案 0 :(得分:0)

This answer适用于本地和不同用户的网络。我使用的是Excel 2013。

我认为RoryA在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")