在 Excel VBA 中,您可以简单地执行以下操作:
Excel.Application.DisplayAlerts = False
这是我在现有文件上保存文件时通常使用的代码。我现在还想检查我试图覆盖的文件是否已打开以供其他用户通过以下功能(我从 SO 获得)进行编辑:
Enum IsFileOpenStatus
ExistsAndClosedOrReadOnly = 0
ExistsAndOpenSoBlocked = 1
NotExists = 2
End Enum
Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus
'ExistsAndClosedOrReadOnly = 0
'ExistsAndOpenSoBlocked = 1
'NotExists = 2
With New FileSystemObject
If Not .FileExists(FileName) Then
IsFileReadOnlyOpen = 2 ' NotExists = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
End With
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select
End Function 'IsFileReadOnlyOpen
因此,当在 Excel VBA 中保存文件时,我会有以下内容:
Excel.Application.DisplayAlerts = False
If IsFileReadOnlyOpen(myFilePathName) <> ExistsAndOpenSoBlocked Then
Excel.ActiveWorkbook.SaveAs myFilePathName, , , , True
End If
Excel.Application.DisplayAlerts = True