在移到下一个文件之前closures文件

该macros循环遍历目录中的所有文件,并将数据格式化为表格。

我需要对表格中的列J从Largest to Smallest进行sorting,然后在移动到下一个文件之前保存文件。 目前它将打开所有的文件。

Sub LoopThroughFiles() FolderName = "C:\Folder1\" If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator Fname = Dir(FolderName & "*.xls") 'loop through the files Do While Len(Fname) With Workbooks.Open(FolderName & Fname) Dim tbl As ListObject Dim rng As Range Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)) Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes) tbl.TableStyle = "TableStyleMedium2" Columns("A:L").Select Columns("A:L").EntireColumn.AutoFit End With 'go to the next file in the folder Fname = Dir Loop End Sub 

您错过了Close工作簿的行: WB.Close True

(如果您不想保存对工作簿所做的更改,请使用WB.Close False

注意 :您没有在打开的工作簿上设置Worksheet对象,因此默认情况下它将采用ActiveSheet ,这是您上次保存此工作簿的最后一个ActiveSheet

试试下面的代码:

 Sub LoopThroughFiles() Dim WB As Workbook FolderName = "C:\Folder1\" If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator fname = Dir(FolderName & "*.xls") Application.ScreenUpdating = False Application.DisplayAlerts = False 'loop through the files Do While Len(fname) Set WB = Workbooks.Open(FolderName & fname) '<-- set the workbook object With WB Dim tbl As ListObject Dim rng As Range Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)) Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes) tbl.TableStyle = "TableStyleMedium2" Columns("A:L").Select Columns("A:L").EntireColumn.AutoFit End With WB.Close True ' <-- close workbook and save changes ' go to the next file in the folder fname = Dir Loop Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub