在本文中,我们将创建一个宏以打印文件夹中的所有Excel文件。

我们要打印的文件夹中有一些Excel文件。它们都具有相同的文件扩展名“ .xlsx”

ArrowFilesInFolder

ArrowMain

代码说明

Dir(TargetFolder&FileFilter)

上面的代码用于获取文件夹路径中第一个文件的文件名。

Workbooks.Open TargetFolder&FileName上面的代码用于打开定义的工作簿。

ActiveWorkbook.PrintOut上面的代码用于打印活动工作簿。

请遵循以下代码

Option Explicit

Sub PrintAllWorkbooksInFolder(TargetFolder As String, FileFilter As String)

'Declaring variable

Dim FileName As String

'Disabling screen updates

Application.ScreenUpdating = False

'Adding path separator in the end of target folder name

If Right(TargetFolder, 1) <> "\" Then

TargetFolder = TargetFolder & "\"

End If

'Assigning default path to file filter

If FileFilter = "" Then FileFilter = "*.xls"

'Get the file name of first file in the folder

FileName = Dir(TargetFolder & FileFilter)

While Len(FileName) > 0

If FileName <> ThisWorkbook.Name Then



'Open workbook

Workbooks.Open TargetFolder & FileName



'Prints all sheets in the workbook

ActiveWorkbook.PrintOut



'Close the workbook without saving any changes

ActiveWorkbook.Close False



End If



'Get file name of next file in the folder

FileName = Dir

Wend

End Sub

Sub CallingProcedure()

'Declaring variables

Dim FolderPath, FileName As String

'Getting values from textbox on sheet1

FolderPath = Sheet1.TextBox1.Value

FileName = Sheet1.TextBox2.Value

'Calling PrintAllWorkbooksInFolder procedure

PrintAllWorkbooksInFolder FolderPath, FileName



End Sub

如果您喜欢此博客,请在Facebook和Facebook上与您的朋友分享。

我们很希望收到您的来信,请让我们知道我们如何才能改善我们的工作并使您的工作更好。写信给我们[email protected]