Excel VBA不保存在当前目录中
这里是我的Excel VBA下面的代码来将Excel文件批量保存为PDF目录。 它使用msoFileDialogFolderPicker来获取用户的input。
一切工作,除了它不保存在当前目录与原始文件,但它保存在上面的文件夹。
请让我知道我需要添加或更改,以便它保存在同一个文件夹中。
谢谢。
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”不存在作为一个variables。
结果,所有传入的都是空string。 因此,默认情况下将文件保存为其现有名称,但在活动目录中保存为.pdf。
您需要将variablesMyPath和MyName传递给sub,否则将它们声明为模块级variables。
例如:选项1: Sub PDFSaveAs(MyPath As String, MyName As String)
称为PDFSaveAs MyPath, MyName
或Option2:在模块顶部将MyPath和MyName声明为Private MyPath As String
等。它们将在PDFSAveAs的范围内。
始终在模块的顶部使用Option Explicit
。 这将确保不会出现像这样的幻像variables的问题。