问题
I am working on a VBA that access a shared excel file to check if the file is used by someone else or not. By that time VBA should not allow other users to access the file in edit mode they should open it in read-only mode if they already opened the file as well. Basically, while I am accessing the same file from the shared path, if it is locked for editing by someone else then this VBA should forcefully change to read-write mode to give edit access to me. And the VBA should allow the other users to open the same file in read-only mode. Once I completed my editing and closed VBA should release the restriction to the other users. Any help on this will appreciated.
Sub wkbk_open()
wkbk_name = "Project List LIVE.xlsm"
wkbk_lock_file_path = "X:\~$" & wkbk_name
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(wkbk_lock_file_path) Then
Debug.Print "The file is locked by " & GetFileOwner(wkbk_lock_file_path)
Debug.Print "The file is locked by " & GetFileOwner2(wkbk_lock_file_path)
Else
Debug.Print "The file is available"
End If
End Sub
Function GetFileOwner(strFileName)
'http://www.vbsedit.com/scripts/security/ownership/scr_1386.asp
Set objWMIService = GetObject("winmgmts:")
Set objFileSecuritySettings = _
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'")
intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
If intRetVal = 0 Then
GetFileOwner = objSD.Owner.Name
Else
GetFileOwner = "Unknown"
End If
End Function
Function GetFileOwner2(strFileName) As String
'On Error Resume Next
Dim secUtil As Object
Dim secDesc As Object
Set secUtil = CreateObject("ADsSecurityUtility")
Set secDesc = secUtil.GetSecurityDescriptor(strFileName, 1, 1)
GetFileOwner2 = secDesc.Owner
End Function
来源:https://stackoverflow.com/questions/62255433/vbscript-to-open-a-shared-file-in-read-write-mode-for-a-particular-username-and