简体   繁体   English

VBA SaveAs方法不保存文件,没有错误?

[英]VBA SaveAs method not saving file, no errors?

Before anyone quickflags this: no, I did not forget to actually save the file after GetSaveAsFilename. 在任何人对此进行快速标记之前:不,我没有忘记在GetSaveAsFilename之后实际保存文件。

Basically, I've got a big VBA module that starts with an Excel file, processes a bunch of data, and generates a summary in Excel. 基本上,我有一个很大的VBA模块,该模块以Excel文件开头,处理大量数据并在Excel中生成摘要。 I want it to be impossible to overwrite the file, and I need it to work in all cases (network drives, opening from email, etc). 我希望它不可能覆盖该文件,并且我需要它在所有情况下都能工作(网络驱动器,从电子邮件打开等)。 This is why I thought it would be best just to open a SaveAs box--leave the onus of the path on the user. 这就是为什么我认为最好只打开一个SaveAs框-将路径的负担留给用户的原因。 However, when I trigger this method by saving with macros enabled, everything behaves as expected except the file itself does not save. 但是,当我通过启用宏进行保存来触发此方法时,除文件本身未保存之外,所有行为均与预期的一样。 The debugger says that fileName is what it should be at the time the SaveAs method is called, so I'm truly stumped here. 调试器说fileName是调用SaveAs方法时应具有的名称,因此我在这里确实很困惑。 There's no error thrown. 没有抛出任何错误。

Thanks to anyone who can help! 感谢任何能提供帮助的人! My code is below: 我的代码如下:

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

Thanks to Kyle's comment on my original question, I've figured out that the solution was to change 感谢凯尔(Kyle)对我的原始问题的评论,我发现解决方案是改变

fileName = Application.GetSaveAsFilename(InitialFileName:=filePath, _
FileFilter:="Microsoft Excel Worksheet (*.xlsx), *.xlsx")

to: 至:

fileName = Application.GetSaveAsFilename(InitialFileName:=filePath, _
FileFilter:="Microsoft Excel Macro-Enabled Worksheet (*.xlsm), *.xlsm")

Ideally I'd be able to get rid of the macros but this answers the question. 理想情况下,我可以摆脱宏,但这可以回答问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM