保存工作簿失败

Save workbook fails

此代码有时有效,有时无效。 我的系统与 onedrive 同步就是这个原因。这里的路径是本地路径。

Dim wb As Workbook
Set wb = Workbooks.Add

wb.SaveAs Filename:=Path & name
wb.Close True

运行时错误

method save as object _workbook failed

我也按照 Microsoft 在 this article 中的建议尝试了 wb.SaveAs Filename:=Path & name, FileFormat:=1

看起来它与 OneDrive 有关,而不是与您的代码有关(至少如果您的文件 path/name 是正确的)。您可以使用错误处理来获取错误消息,并在出现错误时检查 path/file 是否正确。

On Error Resume Next
wb.SaveAs Filename:=Path & name
If Err.Number Then
    MsgBox "File """ & Path & name & """ could not be saved.".
    Debug.Print Path & name
    Exit Sub
End If
On Error Goto 0  ' re-activate error reporting!

wb.Close False

现在您可以检查文件路径和文件名是否正确。

另请注意,wb.Close True 会使您的文件连续保存两次!首先使用 .SaveAs,然后使用 .CloseSaveChanges:=True 参数。所以在同一个文件中连续两次保存一个文件会花费双倍的时间并且没有用。

应该是这样的

Dim wb as Workbook
Dim Path as String

Set wb = Workbooks.Add

Path = ActiveWorkbook.Path & "\" & custom_name & ".xlsm"

ActiveWorkbook.SaveAs fileName:=Path, FileFormat:=51

fileName = custom_name