以下是我的代码,用于Excel VBA将Excel文件作为PDF批量保存在目录中。它使用msoFileDialogFolderPicker来获取用户的输入。
一切正常,但它不会保存在当前目录中的原始文件中,但会保存在上面的文件夹中。
请告诉我需要添加或更改的内容,以便将其保存在同一个文件夹中。
感谢。
Sub BatchProcessing_ExceltoPDF()
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder Location"
.ButtonName = "Select"
.Show
.AllowMultiSelect = False
cmdSelectInput = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems (1) & "\"
End With
MyPath = cmdSelectInput
MyTemplate = "*.xls*" ' Set the template.
MyName = Dir(MyPath & MyTemplate) 'Retrieve the first file
Do While MyName <> ""
Workbooks.Open MyPath & MyName
PDFSaveAs
Workbooks(MyName).Close (True) 'close
MyName = Dir 'Get next file
Loop
MsgBox "Finished Excel Batch Processing"
End Sub
Sub PDFSaveAs()
'
' Save Active Excel Sheet to PDF
'
'
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
MyPath & MyName, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
答案 0 :(得分:2)
在子PDFSaveAs&#34; MyPath&#34;不存在作为变量。
结果传入的所有内容都是空字符串。因此,默认情况下,它将文件保存为现有名称,但在活动目录中保存为.pdf。
您需要将变量MyPath和MyName传递给sub,否则将它们声明为模块级变量。
例如为:
选项1:
Sub PDFSaveAs(MyPath As String, MyName As String)
称为PDFSaveAs MyPath, MyName
或Option2:将模块顶部的MyPath和MyName声明为Private MyPath As String
等。它们将在PDFSAveAs的范围内。
始终在模块顶部使用Option Explicit
。这将确保不会出现像这样的幻像变量的问题。