我有一个汇总文件,可以打开多个 Excel 工作簿并将其中的数据复制到主文件中。该程序几个月来一直运行良好,但在过去的几天里,它在打开某些文件时失败了。我收到以下错误消息。
运行时错误“1004”:
Excel 无法打开文件“filename.xlsm”,因为文件格式或文件扩展名无效。验证文件未损坏,文件扩展名与文件格式匹配未损坏,文件扩展名与文件格式匹配。
如果我点击调试并继续运行程序,则该文件将毫无问题地打开。如果我重新启动程序,它仍然无法打开文件,但它永远不会是相同的文件。当我进入它们并且文件扩展名正确时,我找不到失败的工作簿的任何问题。我有错误处理来检查工作簿中是否还有任何人,所以我认为不可能。
任何帮助将不胜感激,谢谢。
If Not FileLocked(CStr(FoundFiles(iIndex))) Then
On Error GoTo contentErr
Workbooks.Open FoundFiles(iIndex) ', UpdateLinks:=xlUpdateLinksNever
On Error GoTo 0
Application.Run ("'Auto Update Roll-Up.xlsm'!Update")
With Workbooks(tempvar(iIndex - 1))
.Close False
LogInformation ("Completed " & tempvar(iIndex - 1) & " at " & Now)
'Application.EnableEvents = False
'.Close True
'Application.EnableEvents = True
End With
End If
Continue:
Next iIndex
On Error Resume Next
DisplayAlerts = False
Workbooks("Brickman Roll-Up Template.xlsm").Close savechanges:=True
'Workbooks("Brickman Roll-Up Template Test.xlsm").Close savechanges:=True
SetAttr rollupPath, vbReadOnly
Workbooks("Auto Update Roll-Up.xlsm").Close savechanges:=False
DisplayAlerts = True
LogInformation ("Program ended at " & Now)
Application.Quit
contentErr:
If Err.Number = 1004 Then
LogInformation ("_______There is unreadable content in " & Chr(34) & tempvar(iIndex - 1) & Chr(34) & "_______")
GoTo Continue
End If
End Sub
Function FileLocked(strFileName As String) As Boolean
On Error Resume Next
' If the file is already opened by another process,
' and the specified type of access is not allowed,
' the Open operation fails and an error occurs.
Open strFileName For Binary Access Read Write Lock Read Write As #1
Close #1
' If an error occurs, the document is currently open.
If Err.Number <> 0 Then
' Display the error number and description.
LogInformation ("Couldn't open " & strFileName & " because it is already checked out.")
FileLocked = True
Err.Clear
End If
End Function
错误发生在 Workbooks.Open FoundFiles(iIndex) 行