vba 尝试使用文件名中的日期保存文件时,运行时错误 1004 文档未保存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12027718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 17:22:15  来源:igfitidea点击:

Runtime error 1004 Document not saved when try to save file with date in filename

excelexcel-vbasaveruntime-errorvba

提问by user1610138

So I have a macro which work perfectly fine as it is below. It loops through a data validation drop-down and saves a pdf for each country in dropdown. However when I try to edit the macro so that the filename includes the date in addition to the country name (D14) I encounter the runtime error 1004 Document could not be saved. I am very new to VBA so I have no idea how to solve this...I would really really appreciate some help

所以我有一个宏,它可以正常工作,如下所示。它循环遍历数据验证下拉列表,并在下拉列表中为每个国家/地区保存 pdf。但是,当我尝试编辑宏以使文件名除国家/地区名称 (D14) 外还包含日期时,我遇到了运行时错误 1004 无法保存文档。我对 VBA 很陌生,所以我不知道如何解决这个问题......我真的很感激一些帮助

Steph

斯蒂芬

Sub Create_PDFs()
'
' Create_PDFS Macro
'
' Keyboard Shortcut: Ctrl+y
'
Const sheetToExportName = "Graphs"
Const sheetWithCountryList = "Master Sheet"
Const CountryListAddress = "AQ6:AQ38"
Const chosenCountryCell = "D14"
Const sheetWithChosenCell = "Graphs"

Dim CountryList As Range
Dim anyCountry As Range

Set CountryList = _
ThisWorkbook.Worksheets(sheetWithCountryList). _
Range(CountryListAddress)
For Each anyCountry In CountryList
ThisWorkbook.Worksheets(sheetWithChosenCell). _
Range(chosenCountryCell) = anyCountry
ThisWorkbook.Worksheets(sheetToExportName).ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "N:\International Finance Division\RAT Advanced Economies - Chartpacks\Country Risks\Created PDFs\" & ActiveSheet.Range("D14").Value & " - Country Risk Indicators.pdf" _
        , Quality:=xlQualityStandard, IncludeDocProperties:=False, _
        IgnorePrintAreas:=False, OpenAfterPublish:=False
        Next
        Set CountryList = Nothing
End Sub

回答by Daniel

Clean the value of your date of special characters.

清除特殊字符的日期值。

Assuming that range will always be a date, replace:

假设该范围始终是日期,请替换:

ActiveSheet.Range("D14").Value

with something like this:

像这样:

format(ActiveSheet.Range("D14").Value,"YYYYMMDD")

Feel free to use a different format than "YYYYMMDD", but make sure you do not use "/" as indicated by shahkalpesh's comment.

可以随意使用与 不同的格式"YYYYMMDD",但请确保不要使用 shahkalpesh 评论中指出的“/”。