下面是我为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
在子PDFSaveAs中,"MyPath"不作为变量存在。
因此,所有传入的都是一个空字符串。因此,默认情况下,它将文件保存为其现有名称,但在活动目录中保存为.pdf。
您需要将变量MyPath和MyName传递给子,或者将它们声明为模块级变量。
例如:选项1:Sub PDFSaveAs(MyPath As String, MyName As String)
称为PDFSaveAs MyPath, MyName
或者Option2:将模块顶部的MyPath和MyName声明为Private MyPath As String
等。它们将在PDFSAveAs的范围内。
始终在模块顶部使用Option Explicit
。这将确保不会出现类似于幻影变量的问题