Excelmacros:遍历工作簿并打印每个工作表

我需要执行的步骤是重复的,但我不知道如何遍历每个工作簿,然后每个工作表。

我的任务是:

  1. 查看文件夹:(源文件夹)
  2. 迭代该文件夹中的每个工作簿(源文件)
  3. 将每个工作簿中的4个工作表(工作表名称)分别打印到PostScript打印机(打印机名称/path)。
  4. 将打印的文件命名为PS文件=源文件+工作表名称
  5. 最终PS输出文件放置在最终文件夹(目标文件夹)
  6. 原始工作簿已closures并未保存。

我search了迭代VBA /macros,并已经看到了一些想法,但我不确定如何通过工作簿和工作表的代码看起来像。

此外,PS打印机通过打印到文件完成。 这是否会造成问题?

用我刚才试过的代码更新了:

Sub Make_PS_Files() Dim path2 As String, path3 As String path2 = "Drive:\Source folder\" path3 = " Drive:\Destination folder\" Workbooks.Open Filename:=path2 + "File_Name.XLS" Sheets("Specific_Sheet_Name1").Activate Application.ActivePrinter = "\\PRINTER NAME\LOCATION:" ActiveWindow.SelectedSheets.PrintOut copies:=1, PrintToFile:=True, Collate _ :=True, Prtofilename:=True ActiveSheet.PrintOut copies:=1, Prtofilename:=path3 + " Specific_Sheet_Name1.ps" Sheets("Specific_Sheet_Name2").Activate Application.ActivePrinter = "\\VS PRINTER NAME\LOCATION:" ActiveWindow.SelectedSheets.PrintOut copies:=1, PrintToFile:=True, Collate _ :=True, Prtofilename:=True ActiveSheet.PrintOut copies:=1, Prtofilename:=path3 + " Specific_Sheet_Name2.ps" Sheets("Specific_Sheet_Name3").Activate Application.ActivePrinter = "\\ PRINTER NAME\LOCATION:" ActiveWindow.SelectedSheets.PrintOut copies:=1, PrintToFile:=True, Collate _ :=True, Prtofilename:=True ActiveSheet.PrintOut copies:=1, Prtofilename:=path3 + " Specific_Sheet_Name3.ps" ActiveWorkbook.Close Sheets("Specific_Sheet_Name4").Activate Application.ActivePrinter = "\\ PRINTER NAME\LOCATION:" ActiveWindow.SelectedSheets.PrintOut copies:=1, PrintToFile:=True, Collate _ :=True, Prtofilename:=True ActiveSheet.PrintOut copies:=1, Prtofilename:=path3 + " Specific_Sheet_Name4.ps" ActiveWorkbook.Close End Sub 

当我张贴的时候,抱歉我昨晚没有发贴。 它在做什么似乎很长时间。 我认为它可以多一点,所以它更普遍,可以指向任何工作簿和任何数量的表。

并不是所有的工作表都有Specific_Sheet_Name,所以我想遍历而不参考名字。

您可以使用“ 文件夹”和“ 文件”对象,使用FileSystemObject对文件夹中的工作簿进行迭代。 (请记住添加对Microsoft Scripting Runtime的引用)

遍历工作表的迭代就像For Each Workbook.Sheets集合一样简单。

最后,您可以使用每个工作表上的PrintOut方法打印工作表以进行打印。 只要确保将PrintToFile参数设置为true。

如果你需要更多的指导,我build议遵循@ JMax的build议,并发布一些你已经尝试过的东西。

UPDATE

使用FileSystemObject遍历工作簿:

 Sub Make_PS_Files() Dim fso As New Scripting.FileSystemObject Dim source As Scripting.Folder Dim wbFile As Scripting.File Dim book As Excel.Workbook Set source = fso.GetFolder("Drive:\Source folder\") For Each wbFile In source.Files If fso.GetExtensionName(wbFile.Name) = "xls" Then Set book = Workbooks.Open(wbFile.Path) ' Print out the workbook End If Next End Sub 

并遍历工作簿中的工作表:

 Dim sheet As Excel.Worksheet For Each sheet in book.Sheets sheet.PrintOut Copies:=1, ActivePrinter:="\\Printer:", PrintToFile:=True, _ PrToFileName:=fso.BuildPath(destination, sheet.Name & ".ps") Next 

请记住,这没有error handling,但我希望它有帮助。