VBA带日期添加的条件另存为
我正在使用Excel 2010,并尝试使用宏执行以下操作:VBA带日期添加的条件另存为,vba,excel,excel-2010,save-as,Vba,Excel,Excel 2010,Save As,我正在使用Excel 2010,并尝试使用宏执行以下操作: 打开“另存为”对话框 取初始文件名,检查文件类型(即xlsx)前是否有下划线后跟8个连续整数(即_12345678) 如果确实存在,请将其删除并替换为在文件类型(ie..xlsx)之前加上下划线,后跟“yyyymmdd”格式的今天的日期(即_20130730) 如果不存在,只需在文件类型(即.xlsx)之前添加一个下划线,后跟“yyyymmdd”格式的今天的日期(即_20130730) 基于上述条件的新文件名将出现在“打开另存为”对话框
1.测试文件A_20130615.xlsx将成为测试文件A_20130730.xlsx
2.测试文件B.xlsx将变成测试文件B_20130730.xlsx 感谢您的任何帮助!
谢谢我修改了一个例程,它执行与您尝试执行的相同类型的操作,但使用文件的当前名称,而不是使用两个保存对话框
Option Explicit
Function SaveIt()
Dim CurrentFile As String
Dim FileExt As String
Dim GetFileName
CurrentFile = Left(ActiveWorkbook.FullName, InStrRev(ActiveWorkbook.FullName, ".") - 1)
FileExt = Mid(ActiveWorkbook.FullName, InStrRev(ActiveWorkbook.FullName, "."))
If InStr(CurrentFile, "_") Then
'has underscore
If InStrRev(CurrentFile, "_") = Len(CurrentFile) - 8 Then
' underscore 8 from end
If Right(CurrentFile, 8) = CStr(Val(Right(CurrentFile, 8))) Then
' and it's 8 digits at the end
CurrentFile = Left(CurrentFile, Len(CurrentFile) - 9)
'strip the end off
End If ' if it fails any of these tests,
End If 'then it's not got the underscore and date
End If ' and we don't touch the filename
CurrentFile = CurrentFile & "_" & Format(Now, "yyyymmdd")
GetFileName = Application.GetSaveAsFilename(CurrentFile & FileExt)
If GetFileName <> False Then 'Cancel returns false, otherwise it returns the filename
ActiveWorkbook.SaveAs GetFileName
End If
End Function
选项显式
函数SaveIt()
将当前文件设置为字符串
Dim FileExt作为字符串
Dim GetFileName
CurrentFile=Left(ActiveWorkbook.FullName,InStrRev(ActiveWorkbook.FullName,“.”)1)
FileExt=Mid(ActiveWorkbook.FullName,InStrRev(ActiveWorkbook.FullName,“.”)
如果InStr(CurrentFile,“u”)则
"有下划线,
如果InStrRev(CurrentFile,“”)=Len(CurrentFile)-8,则
'从末尾下划线8
如果Right(CurrentFile,8)=CStr(Val(Right(CurrentFile,8)),则
“最后是8位数字
CurrentFile=Left(CurrentFile,Len(CurrentFile)-9)
"剥去末端,
如果“未通过任何这些测试,则结束”,
如果结束,则它没有下划线和日期
如果“结束”,则我们不接触文件名
CurrentFile=CurrentFile&“&”格式(现在为“yyyyymmdd”)
GetFileName=Application.GetSaveAsFilename(CurrentFile&FileExt)
如果GetFileName为False,则“取消”返回False,否则返回文件名
ActiveWorkbook.SaveAs GetFileName
如果结束
端函数
这也允许人们拥有名为test_1.xlsx和的文件,而不必担心名称被破坏,但在现实生活中,我宁愿使用RegEx来获取名称。