对象“_Workbook”的运行时错误“1004”方法“保存”失败

运行VBA应用程序时出现此错误。 我认为这个错误是与我的代码中的以下行有关

ActiveWorkbook.Save 

这是整个代码。

 LDate = Date LDate = Mid(LDate, 4, 2) If LDate > 8 Then Sheets("a").Cells(13, "H").Value = Sheets("a").Cells(13, "H").Value + 1000 Else Sheets("a").Cells(13, "H").Value = Sheets("a").Cells(13, "H").Value + 1 End If ActiveWorkbook.Save 

有人可以解释这个错误的原因,以及我可以如何解决它。

请阅读下面的评论。

这是在单击第一个button时执行的子例程。

 Sub import() Dim Filt As String Dim FilterIndex As Integer Dim Title As String Dim FileName As Variant Dim finalrow As Integer Dim alldata As String Dim temp As String Dim oFSO As New FileSystemObject Dim oFS As TextStream 'Filt = "Cst Files (*.txt),*.txt" 'Title = "Select a cst File to Import" 'FileName = Application.GetOpenFilename(FileFilter:=Filt, Title:=Title) 'If FileName = False Then 'MsgBox "No File Was Selected" 'Exit Sub 'End If 'Call TestReference ' Open the file dialog Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) diaFolder.AllowMultiSelect = False diaFolder.Show If diaFolder.SelectedItems.Count <> 0 Then folderpath = diaFolder.SelectedItems(1) folderpath = folderpath & "\" 'MsgBox diaFolder.SelectedItems(1) Set diaFolder = Nothing 'RefreshSheet On Error Resume Next temp = folderpath & "*.txt" sFile = Dir(temp) Do Until sFile = "" inputRow = Sheets("RawData").Range("A" & Rows.Count).End(xlUp).Row + 1 FileName = folderpath & sFile Set oFS = oFSO.OpenTextFile(FileName) Dim content As String content = oFS.ReadAll content = Mid(content, 4, Len(content) - 3) With Sheets("RawData").Range("A" & inputRow) .NumberFormat = "@" .Value = content End With oFS.Close Set oFS = Nothing alldata = "" finalrow = Sheets("RawData").Cells(Rows.Count, 1).End(xlUp).Row Sheets("RawData").Activate For i = inputRow To finalrow alldata = alldata & Cells(i, "A").Value & " " Cells(i, "A").Value = "" Next i Cells(inputRow, "B").Value = alldata temp = StrReverse(FileName) temp = Left(temp, InStr(1, temp, "\") - 1) temp = StrReverse(temp) temp = Left(temp, InStr(1, temp, ".") - 1) Cells(inputRow, "A").Value = temp Sheets("RawData").Cells(inputRow, "A").NumberFormat = "@" sFile = Dir() Loop Else MsgBox ("No Folder Selected") End If End Sub 

如何使此代码在执行此macros后停止访问工作表?

尽pipe我认为你应该认真考虑重构你的代码 ,你应该首先引用由.Save()方法调用的正确的工作簿。

  Workbooks("Insert_Workbook_Name_Here.xlsm").Save 

确保工作簿名称和扩展名(.xlsm,.xls,.xlsx)与您实际尝试保存的文件相匹配。

这个错误发生在我写的macros中。 我有这个代码closures对话框。

 Private Sub CancelButton_Click() Unload Me ThisWorkbook.Save End End Sub 

我收到了同样的错误,因为正在加载的工作簿来自“上次保存”的副本,原因是在原始打开时发生了更新重新启动。 不知道如何避免在未来,但认为这可能会有所帮助。