我需要执行的步骤是重复的,但我不确定如何遍历每个工作簿,然后是每个工作表。
我的任务是:
我搜索了迭代 VBA/Macro 并看到了一些想法,但我不确定代码在处理工作簿和工作表时的外观。
此外,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 遍历文件夹中的工作簿。通过使用 Folder和 File对象。 (记得添加对 Microsoft Scripting Runtime
的引用)
遍历工作表就像 For Each
一样简单超过 Workbook.Sheets
收藏。
最后,您可以使用 PrintOut 打印工作表。每个工作表上的方法来打印它们。只需确保设置 PrintToFile
参数为真。
如果您需要更多的指导,我建议您遵循@JMax 的建议并发布您已经尝试过的一些内容。
更新
使用 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
请记住,这没有错误处理,但我希望它有所帮助。
关于Excel 宏 : iterate through workbooks and print individual sheets from each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9021468/