My brilliant colleagues reminded me of the Excel lock file. When you open excel, you create a hidden system file that stores the names of the people who have the file open. The lock file begins with "~ $" before the table name. Example:
If you have a spreadsheet called testWorkbook.xlsx , then the lock file will be ~$testWorkbook.xlsx located in the same directory.
It is also a faster and easier way to check if a file is open, because you are not actually opening the file, as I did before. Now I just check if the lock file exists, and if so, I check who the "owner" of the lock file is, and that will be the one who has the spreadsheet currently open. Hope this helps someone in the future!
This is my code that works flawlessly:
testWorkbookLockFile = "I:\~$test_workbook.xlsx" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(testWorkbookLockFile) Then WScript.Echo "The file is locked by " & GetFileOwner(testWorkbookLockFile) Else WScript.Echo "The file is available" End If 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
I want to point out that I did not write the GetFileOwner Function gut. I contacted the website where I got this code in a function.
In addition, if you do not have a location mapped to a spreadsheet, and it is on the network, the UNC path will not work, you need to map the drive. This can be done using the following 2 lines of code:
Set objNetwork = WScript.CreateObject("WScript.Network") objNetwork.MapNetworkDrive "Z:", "\\Server1\Share1"
Hope someone benefits from this. I know that there is not much information on how to do this on the Internet, since I have always looked for it!
Steven
source share