我去了使用共享文件的方向。但是后来发现是excel共享的文件有很多bug。如果使用共享文件,excel/宏可能会非常慢,间歇性崩溃,有时整个文件可能会损坏,之后无法打开或修复。还取决于有多少用户使用该文件,文件大小会变得相当大。所以最好不要使用共享工作簿。完全不值得尝试。相反,如果需要多个用户同时更新数据,最好使用一些数据库,例如MSAccess,MSSql(Update MSSQL from Excel)等与excel。对于我的情况,由于用户数量较少,我没有使用任何数据库,而是提示用户等到其他用户关闭该文件。请查看以下代码以检查文件是否已打开,如果已打开,则提示用户。我从堆栈溢出本身获得了这段代码,并根据我的需要进行了修改。
如下调用模块TestFileOpened。
Sub fileCheck()
Call TestFileOpened(plannerFilePathTemp)
If fileInUse = True Then
Application.ScreenUpdating = True
Exit Sub
End If
End Sub
这里的plannerFilePathTemp 是原始文件的临时文件位置。每当打开一个 excel 文件时,都会创建一个临时文件。例如,您的原始文件位置如下
plannerFilePath = "C:\TEMP\XXX\xxx.xlsx"
因此您的临时文件位置将是
plannerFilePathTemp = "C:\TEMP\XXX\~$xxx.xlsx"
或者换句话说,临时文件名将是~$xxx.xlsx
Call TestFileOpened(plannerFilePathTemp)会调用以下代码
Public fileInUse As Boolean
Sub TestFileOpened(fileOpenedOrNot As String)
Dim Folder As String
Dim FName As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(fileOpenedOrNot) Then
fileInUse = True
MsgBox "Database is opened and using by " & GetFileOwner(fileOpenedOrNot) & ". Please wait a few second and click again", vbInformation, "Database in Use"
Else
fileInUse = False
End If
End Sub
Function GetFileOwner(strFileName)
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
我在使用共享文件时也遇到了内存不足的问题。所以在这个过程中,我想出了以下方法来最小化内存消耗
Some tips to clear memory