尝试将工作簿保存到用户指定的文件夹

您好,我正在尝试制作一个macros,将报告保存到特定的文件夹。 我们的文件夹每天都会生成,如C://Report_Type/2017/11/10 (其中/10是我要保存文件的文件夹)。

我所提供的代码提示用户提供date以使文件夹位于其中,然后按照指定的名称保存文件。

但是,当我运行macros时,它将文件保存在C://Report_Type/2017/11根文件夹中,忽略基于userinput的date。 有人能帮我解决错误吗?

解释起来有点复杂,但如果你检查代码,那么这是有道理的。

 Sub PSSaveFile() Dim myVal2 As Variant Dim myDate As String Dim mFilePath As String myVal2 = InputBox("Please enter today's date in mm\dd format") myDate = Date - 1 mFilePath = "\\sample\sample_emea\sec_REPORTS\APPS\Reports\Regional\sample_security_app\2017\" & myVal2 ActiveWorkbook.SaveAs FileName:=mFilePath & "SampleLogs-" & myDate & "-12352_checked" End Sub 

感谢您的帮助提前!

为什么这么复杂? 我的意思是,为什么要求自动获取date?

这是你正在尝试(未testing)?

 Sub PSSaveFile() Dim FilePath_A As String, FilePath_B As String, FilePath_C As String Dim sFile As String FilePath_A = "\\sample\sample_emea\sec_REPORTS\APPS\Reports\Regional\sample_security_app\2017\" FilePath_B = Format(Date, "mm\dd") FilePath_C = "\SampleLogs-" & Replace(Date - 1, "/", "-") & "-12352_checked.xlsx" sFile = FilePath_A & FilePath_B & FilePath_C ActiveWorkbook.SaveAs sFile, 51 End Sub 

一些事情

  1. 命名文件避免使用像\ / : * ? " < > |这样的特殊字符\ / : * ? " < > | \ / : * ? " < > |因此我们在上面的代码中使用了Replace(Date - 1, "/", "-")
  2. 提及文件扩展名和文件格式编号
  3. 打破你的代码易于理解的“部分”。 使得更容易理解和pipe理代码。

是的,这是一个更简单的方法,不幸的是,使用macros的用户经常检查积压,所以她所检查的date并不总是今天或昨天的date,因此userinput函数 – Rhyfelwr 14分钟前

既然你使用的是InputBox,你可能想用这个

 Sub PSSaveFile() Dim FilePath_A As String, FilePath_B As String, FilePath_C As String Dim sFile As String Dim Ret As Variant Ret = InputBox("Please enter date in mm\dd format") If Ret = "" Then Exit Sub FilePath_A = "\\sample\sample_emea\sec_REPORTS\APPS\Reports\Regional\sample_security_app\2017\" FilePath_B = Ret '~~> Check if the folder path exists If FileFolderExists(FilePath_A & FilePath_B) Then FilePath_C = "\SampleLogs-" & Replace(Date - 1, "/", "-") & "-12352_checked.xlsx" sFile = FilePath_A & FilePath_B & FilePath_C ActiveWorkbook.SaveAs sFile, 51 Else MsgBox "The folder path " & FilePath_A & FilePath_B & " doesn't exist" End If End Sub Public Function FileFolderExists(strFullPath As String) As Boolean On Error GoTo Whoa If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True Whoa: On Error GoTo 0 End Function