[英]ThisWorkbook.SaveAs Filename doesn't save and no error code (that I see)
[英]VBA ThisWorkbook.SaveAs Filename:=SaveAsName custom name (SaveAsName) not appearing in dialog
我希望有人可以帮助我。 我正在使用VBA在Excel中创建模型,并希望使用自定义文件名填充“另存为”对话框。 我有三段代码。 第一种是针对要求最终用户输入其设施名称的用户表单:
Private Sub cmdNext_Click()
strHospName = frmHospName.txtHospName.Value
' Check for a usable hospital name
If Len(strHospName) = 0 Then
frmHospName.Hide
MsgBox "Please provide the name of your facility.", vbCritical + vbOKOnly, "Missing Facility Name"
frmHospName.Show
End If
If (Len(strHospName) - Len(Trim(strHospName)) = Len(strHospName)) Then
frmHospName.Hide
MsgBox "Please provide the name of your facility.", vbCritical + vbOKOnly, "Missing Facility Name"
frmHospName.Show
End If
If strHospName Like "*[\/:*?""<>|]*" Then
frmHospName.Hide
MsgBox "Please enter your facility's name without any of the following characters: \ / : * ? < > | ", vbCritical + vbOKOnly, "Invalid Facility Name"
frmHospName.Show
End If
Call SaveAsNameStore(strHospName, MyName)
Set currForm = Me
Unload Me
End Sub
第二部分位于其自己的模块中,并检查该模型是否已被自定义(自定义模型在打开工作簿时将不会看到frmHospName,因此不会分配strHospName),并基于该检查创建字符串SaveAsName :
Public strHospName As String
Public SaveAsName As String
Function MyName() As String
MyName = ThisWorkbook.Name
End Function
Sub SaveAsNameStore(strHospName As String, MyName As String)
' This code creates a custom SaveAs name
Dim strModelDate As String
strModelDate = Format(Now, "mm-dd-yyyy")
If (Len(strHospName) - Len(Trim(strHospName)) = Len(strHospName)) Then
SaveAsName = MyName
Else
SaveAsName = strHospName & " customized economic model " & strModelDate
End If
End Sub
第三部分位于ThisWorkbook中,并在Workbook_BeforeSave中应用SaveAsName:
Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
''This code forces SaveAs with custom filename instead of Save to prevent overwriting the master model file
''NEED TO UNCOMMENT PRIOR TO DELIVERY
Application.ScreenUpdating = False
If SaveAsUI = False Then
Cancel = True
ElseIf SaveAsUI = True Then
With Application.FileDialog(msoFileDialogSaveAs)
Application.EnableEvents = False
If .Show Then
ThisWorkbook.SaveAs Filename = SaveAsName
End If
Application.EnableEvents = True
End With
Cancel = True
End If
End Sub
问题是,当我单击“另存为”按钮时,对话框中没有填充自定义的“另存为”名称。 我可以看到通过即时窗口中的?SaveAsName
正确生成了?SaveAsName
。 对于语法,我尝试了ThisWorkbook.SaveAs Filename = SaveAsName
和ThisWorkbook.SaveAs Filename:=SaveAsName
,但结果相同。
对不起,这个冗长的帖子。 我会很感激您能提供的任何帮助!
这是我用来备份当前正在使用的内容的东西,而没有命名相同的内容。 轻松修改您的情况和变量
Private Sub cmdBackupButton_Click()
'__BACKUP THE CURRENT WORKBOOK___
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs "C:\WhateverPathYouWant\myFile_backup.xlsb")
Application.DisplayAlerts = True
End Sub
这消除了任何“另存为”对话,并且不需要交互。 很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.