通过一次打开并保存工作表来循环访问文件并保护工作表

时间:2018-01-09 01:42:50

标签: excel vba excel-vba

我正在处理200多个excel文件,我需要保护我的Excel工作表,然后才能将其发送给其他公司。下面的代码设法工作,但问题是它继续打开文件夹中的所有excel文件,直到内存不足以进行处理,我还必须手动保存所有打开的文件

有没有一种方法可以让代码一次一个地循环文件夹中的excel文件并在继续下一个excel文件之前保存它?

Sub LoopThroughFiles()

    FolderName = "C:\Users\Desktop\PROJECTS\PROJECT FILE\A"
    If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
    Fname = Dir(FolderName & "*.xlsx")

    'loop through the files
    Do While Len(Fname)

        With Workbooks.Open(FolderName & Fname)

           ' here comes the code for the operations on every file the code finds

        ActiveSheet.Protect "password", True, True


        End With

        ' go to the next file in the folder
        Fname = Dir

    Loop

End Sub

1 个答案:

答案 0 :(得分:0)

Sub LoopThroughFiles()

    FolderName = "C:\Users\Desktop\PROJECTS\PROJECT FILE\A"
    If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
    Fname = Dir(FolderName & "*.xlsx")

    'loop through the files
    Do While Len(Fname)

        With Workbooks.Open(FolderName & Fname)

           ' here comes the code for the operations on every file the code finds

        ActiveSheet.Protect "password", True, True
        .save
        .close

        End With

        ' go to the next file in the folder
        Fname = Dir

    Loop

End Sub