vba -当文件名随日期不断变化时打开特定的文件



我在Excel 2016中有一个宏,目前可以打开特定的电子邮件模板。该模板需要将表单添加为附件。我当前的代码可以打开文件的位置,但随后用户必须找到/选择正确的文件。

我如何得到VBA打开所需的形式,而不仅仅是文件夹?我知道文件名&路径,但文件名会随着版本而不断更改。我能找到的所有线程都涉及已知的文件名和未知的路径。这是已知路径部分已知文件名由于文件的周期性,

交货。今天是十月,但最新的版本是C:filepathForm_Sept_2021.pdf,以前的日期版本已经移到存档文件夹。

Sub Open_Template()
Dim myolapp As Object
Dim myitem As Object
Dim answer As Integer
answer = MsgBox("Do you still need to create the required form?", vbQuestion + vbYesNo + vbDefaultButton1, "Form Required")
Set myolapp = CreateObject("Outlook.Application")
myolapp.Session.Logon
'This is the email that requires a form attached
Set myitem = myolapp.CreateItemFromTemplate("C:\filepathemail.oft")
myitem.Display
'This part needs modified to open the pdf file from the above example
If answer = vbYes Then
Call Shell("explorer.exe" & " " & "C:\filepath" vbNormalFocus)
End If
End Sub 

我认为你可以像上面建议的那样在文件名中使用一个变量。您可以将变量赋值为月份("Mmmm"),然后将其插入。您可以使用if语句来测试当前月份,然后尝试返回一个月。

可以是这样的:

Dim LastMonth   As Date
Dim Period      As String
Dim FileName    As String
' Other code.
If answer = vbYes Then
LastMonth = DateAdd("m", -1, Date)
Period = "Form_" & Left(Format(LastMonth, "mmmm"), 4) & Format(LastMonth, "_yyyy")
FileName = "C:\filepath\" & Period & ".pdf"
Call Shell("explorer.exe" & " " & FileName, vbNormalFocus)
End If

不确定双反斜杠。

您需要将表单附加到邮件中吗?您应该能够使用Dir("C:filepathForm*.pdf")来查找匹配的表单文件名,其中*是名称的可变部分。- - - - - -Tim Williams

由于文件名称上的日期可能取决于它最近更新的时间,因此我发现可以使用带有通配符的Dir命令来帮助查找Tim建议的目录中的文件。然后我让excel打开那个文件。

Dim form As String
'Same code as before up through the If/Then statement
If answer = vbYes Then
'Find the file name where it is the only pdf in the directory starting with "Form"
form = Dir("C:\filepathForm*.pdf")
'Use Excel to open the file in the appropriate program
ActiveWorkbook.FollowHyperlink "C:\filepath" & form
End If

虽然,我也可以指定程序打开文件在使用Call Shell("program.exe" "C:filepath" & form)其中program.exeAcroRd32.exe为Adobe或任何其他选择的exe查看文件。

最新更新