在任何人快速标记之前:不,我没有忘记在GetSaveAsFilename之后实际保存文件。
基本上,我有一个大的VBA模块,它以Excel文件开头,处理大量数据,并在Excel中生成摘要。我希望它不可能覆盖文件,我需要它在所有情况下工作(网络驱动器,从电子邮件打开等)。这就是为什么我认为最好只打开一个SaveAs框 - 让路径的责任留给用户。但是,当我通过保存启用宏来触发此方法时,除文件本身不保存外,一切都按预期运行。调试器说fileName是在调用SaveAs方法时它应该是什么,所以我真的很难过。没有错误抛出。
感谢任何可以提供帮助的人!我的代码如下:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim fileName As String, oldName As String, fullName As String
Dim fragName() As String, noExtension As String, filePath As String
Dim newName As String
Cancel = True
oldName = ThisWorkbook.Name
fullName = ThisWorkbook.fullName
fragName() = Split(fullName, ".", 2)
noExtension = fragName(0)
filePath = ThisWorkbook.Path & "\"
Application.enableEvents = False
enterName:
fileName = Application.GetSaveAsFilename(InitialFileName:=filePath, _
FileFilter:="Microsoft Excel Worksheet (*.xlsx), *.xlsx")
On Error GoTo getOut
If fullName = fileName Then
MsgBox ("You have chosen the same name, " & oldName & vbCr _
& ", please choose something different.")
GoTo enterName
ElseIf fileName = "False" Then GoTo getOut
End If
ThisWorkbook.SaveAs (fileName)
getOut:
Application.enableEvents = True
End Sub
答案 0 :(得分:0)
感谢Kyle对我原来问题的评论,我发现解决方案是要改变
fileName = Application.GetSaveAsFilename(InitialFileName:=filePath, _
FileFilter:="Microsoft Excel Worksheet (*.xlsx), *.xlsx")
为:
fileName = Application.GetSaveAsFilename(InitialFileName:=filePath, _
FileFilter:="Microsoft Excel Macro-Enabled Worksheet (*.xlsm), *.xlsm")
理想情况下,我能够摆脱宏,但这回答了这个问题。