关于EXCEL模板自动生成文件名的问题

2024-12-19 00:33:13
推荐回答(2个)
回答1:

问题说清楚了,解决就简单了。

只是还有一点没说清楚
“在C3和F12单元格没有值的情况下,不能保存”

我现在写的是两个必须都有数据,如果一个有数据就可以,把
If [C3] = "" Or [F12] = "" Then
改成
If [C3] = "" AND [F12] = "" Then

代码如下:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim zPATH As String
If [C3] = "" Or [F12] = "" Then
MsgBox "C3和F12单元格必须有数据!", vbCritical, "错误"
Cancel = True
Else
zPATH = Application.GetSaveAsFilename([C3] & "字符串1" & [F12] & "字符串2.xls", fileFilter:="Excel Files (*.xls), *.xls")
If zPATH = "FALSE" Then
Cancel = True
Else
Application.EnableEvents = False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=zPATH, FileFormat:=xlNormal
Application.DisplayAlerts = True
Application.EnableEvents = True
End If
End If
End Sub

回答2:

把保存文件的过程录制为宏,查看宏,就知道该怎么写命令了。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
ActiveWorkbook.SaveAs Filename:="D:\My Documents\" & [c3] & "xxx" & [f12] & ".xls"
End Sub