Excelmacros – 导出为PDF

我有一个工作手册,有许多macros导出各种工作表作为PDF格式在工作簿保存在同一位置。

我的问题是,如果工作簿保存在桌面上的文件夹,那么PDF生成就好了。

当工作簿保存在networking位置时,pdf不会生成。 下面是macros的一个例子:

Sub PDF_CStmtP() Application.ScreenUpdating = False ThisWorkbook.Sheets(Array("C Stmt - P")).Select pdfname = fileSaveName ChDir ActiveWorkbook.Path & "\" fileSaveName = "Closing Statement (Purchase)" ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ fileSaveName _ , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _ :=False, OpenAfterPublish:=False Application.ScreenUpdating = True ActiveWorkbook.Sheets("Main Menu").Activate MsgBox "File Saved " & " " & fileSaveName End Sub 

你的问题是ChDir命令,在这里看到一个解释: https : //www.techonthenet.com/excel/formulas/chdir.php

其中重要的部分是“CHDIR语句可以让你改变当前驱动器上的当前目录,如果你需要改变驱动器,首先尝试使用CHDRIVE语句。

当你试图保存到一个networking驱动器时,你正在将驱动器盘符从C:\更改为networking驱动器映射到的任何地方,在我的情况下是U:\。

对代码的简单修复就是将path从ChDir移动到文件名中,所以你的代码应该如下所示:

 Sub PDF_CStmtP() Application.ScreenUpdating = False ThisWorkbook.Sheets(Array("C Stmt - P")).Select pdfname = fileSaveName 'ChDir ActiveWorkbook.Path & "\" fileSaveName = ActiveWorkbook.Path & "\" & "Closing Statement (Purchase)" ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _ Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=False Application.ScreenUpdating = True ActiveWorkbook.Sheets("Main Menu").Activate MsgBox "File Saved " & " " & fileSaveName End Sub 

还有一些其他的编辑可以用来清理它,但是这样可以解决这个问题。

**基于关于消息框的评论,您可以将代码更改为:

 Sub PDF_CStmtP() Application.ScreenUpdating = False ThisWorkbook.Sheets(Array("C Stmt - P")).Select pdfname = "Closing Statement (Purchase)" 'ChDir ActiveWorkbook.Path & "\" fileSaveName = ActiveWorkbook.Path & "\" & pdfname ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _ Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=False Application.ScreenUpdating = True ActiveWorkbook.Sheets("Main Menu").Activate MsgBox "File Saved " & " " & pdfname End Sub