在移动到下一个文件之前关闭文件

时间:2017-05-09 17:55:49

标签: excel vba excel-vba

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

我需要将表格中的列J从最大值排序到最小值,然后保存文件,然后再转到下一个文件。目前,它会打开所有文件。

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

1 个答案:

答案 0 :(得分:1)

您错过了工作簿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