我试图通过打开文件的读/写来将它锁定在内存中的一个小型虚拟文本文件上,这样我就可以对另一个打开的共享xlsm中的某些共享Excel表进行独占访问。进行必要的修改后,我将关闭文件以允许其他用户锁定它,并在必要时修改共享的xlsm。
<< [Open和FSO.OpenTextFile命令在本地文件上可以正常工作。但是,我无法使用“https://d.docs.live.net/.....”文件路径来工作。他们抛出运行时错误。
Workbooks.Open
可以处理这样的路径名(在我阅读并测试自己in another SO post时),但我不想在Excel中打开文件,只需将其锁定在操作系统级别的内存中,直到完成操作即可修改。Public Sub GetExclusiveAccess()
Dim fso As FileSystemObject
Dim txtStream As TextStream
Dim filepath As String
Dim PathDelimiter As String
PathDelimiter = IIf(InStr(ThisWorkbook.Path, "//") > 0, "/", "\")
filepath = ThisWorkbook.Path & PathDelimiter & "filelock.txt"
' First method
Set fso = New FileSystemObject
'On Error Resume Next
Set txtStream = fso.OpenTextFile(filepath, ForWriting, False)
'On Error GoTo 0
If txtStream Is Nothing Then GoTo Error
'Success...
txtStream.Close
' Second method
Open filepath For Output As #1
'Success...
Close #1
Error:
End Sub
我有一个文本文件,其单词“ open”或“ closed”取决于打开共享数据库文件的值。
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(TXT_File_Path, 1)
Contents = objFile.ReadLine
DoEvents
objFile.Close
if Contents = "Open" then
' output error
else
' open file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(TXT_File_Path)
objFile.WriteLine "Open" ' write open in the text file
objFile.Close
Set FSO = Nothing
Set oFile = Nothing
' do your stuff
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(TXT_File_Path)
objFile.WriteLine "Closed" ' write Closed in the text file
objFile.Close
Set FSO = Nothing
Set oFile = Nothing
end if
我还相信我在Microsoft帮助页面上找到了一个名为IsWorkBookOpen的功能。
Function IsWorkBookOpen(FileName As String) Dim ff As Long, ErrNo As Long On Error Resume Next ff = FreeFile() Open FileName For Input Lock Read As #ff Close ff ErrNo = Err On Error GoTo 0 Select Case ErrNo Case 0: IsWorkBookOpen = False Case 70: IsWorkBookOpen = True Case Else: Error ErrNo End Select End Function
如果打开或关闭工作簿(Excel),则返回true / false。但是我主要依靠文本文件,因为它速度更快,并且可以保存额外的信息(我的文件是最新打开的)。我还建议您更改为xlsb文件,因为它们比xlsm更快。当通过网络仅到达大约2 MB的文件时,拥有需要多次打开和关闭的数据库文件会花费很长时间。