我在 Excel 2016 中有一個宏,目前可以打開特定的電子郵件模板。該模板需要將表單添加為附件。我當前的代碼可以打開檔案的位置,但是用戶必須找到/選擇正確的檔案。
如何讓 VBA 打開所需的表單而不僅僅是檔案夾?我知道檔案名和路徑,但檔案名隨著版本不斷變化。我能找到的所有執行緒都涉及已知檔案名和未知路徑。由于檔案的周期性,這是一個已知的路徑和部分已知的檔案名。
前任。今天是 10 月,但最新版本是C:\filepath\Form_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:\\filepath\email.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
uj5u.com熱心網友回復:
我認為您可以按照上面的建議在檔案名中使用變數。您可以將變數分配為月份(“Mmmm”),然后將其插入。您可以使用 if 陳述句來測驗當前月份,然后嘗試回傳一個月。
uj5u.com熱心網友回復:
它可能是這樣的:
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
不確定雙反斜杠。
uj5u.com熱心網友回復:
您需要在郵件中附上表格嗎?您應該能夠使用 Dir("C:\filepath\Form*.pdf") 找到匹配的表單檔案名,其中 * 是名稱的可變部分。— 蒂姆·威廉姆斯
由于名稱上的檔案日期可能會根據最近更新的時間而有所不同,我發現我可以使用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:\\filepath\Form*.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.exe是Adobe 的AcroRd32.exe或任何其他選擇的exe查看檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328286.html
標籤:擅长 vba 文件 自动化 excel-2016
