我正在修改我通过Vertex42在线找到的甘特图excel模板,以增加功能。
其中一种修改是在名为“ Config”的工作表中的一个复选框,当选中该复选框时,只要打开该文档,便会创建甘特图的备份。
由于某种原因,我无法完成这个简单的任务。
我尝试同时使用Form控件和ActiveX控件复选框,并带有不同的错误消息。据我所知,不建议使用Form控件,因此,根据我在网上看到的内容,我在ThisWorkbook excel对象中使用以下代码。
Private Sub Workbook_open()
Dim backupFilename As String
Dim formattedDateTime As String
If Sheets("Config").OLEObjects("AutoBackupCheckbox").Object.Value = True Then
formattedDateTime = Format(Now, "d-MMMM-yyyy, h:mm:ss")
backupfilename = Replace(ActiveWorkbook.Name, ".xlsm", " - backup " & DateTime & ".xlsm")
ActiveWorkbook.SaveCopyAs (backupfilename)
End If
End Sub
每次打开文档或运行调试器时,这段代码都会向我显示错误消息,
Run-time error '1004':
Sorry, we couldn't find the <filename> - backup <day>-<month>-<year>, <hour>:<minute>:<seconds>.xlsm. Is it possible it was moved, renamed or deleted?
有什么想法吗?
更新:运行调试器后,它在ActiveWorkbook.SaveAs
行上抱怨。
更新2:更改了'backupFilename'的格式以删除中间的'.xlsm'。
更新3:用不带斜杠的日期/时间替换日期,并用SaveCopyAs替换SaveAs。更新了错误消息。
答案 0 :(得分:0)
SaveCopyAs调用的参数缺少文件的路径。
替换为
Private Sub Workbook_open()
Dim backupFilename As String
Dim formattedDate As String
Dim tempFilename As String
Dim workingPath As String
Dim i As Integer
i = 1
If Sheets("Config").OLEObjects("AutoBackupCheckbox").Object.Value = True Then
formattedDate = Format(Date, "d-MMMM-yyyy, ver " & i)
workingPath = Application.ActiveWorkbook.FullName
backupFilename = Replace(workingPath, ".xlsm", " - backup " & formattedDate & ".xlsm")
tempFilename = Dir(backupFilename)
While tempFilename <> "" ' if file already exists
i = i + 1
formattedDate = Format(Date, "d-MMMM-yyyy, ver " & i)
backupFilename = Replace(workingPath, ".xlsm", " - backup " & formattedDate & ".xlsm")
tempFilename = Dir(backupFilename)
Wend
ActiveWorkbook.SaveCopyAs (backupFilename)
End If
End Sub