为什么此循环找不到我在那里的文件?

时间:2019-01-11 13:55:46

标签: excel vba

每次该脚本都要保存Wb时,都说找不到该文件,并询问是否已将其删除或放置在其他位置?

文件位于我指定的正确文件夹路径中,这可能导致此错误吗?

我编辑了代码,这行是调试器停止的地方:

    Set Wb = Workbooks.Open(fileName)

Sub passwordprotect()

Dim fileName As Variant
Dim Wb As Workbook

folderpath = "C:\Realty Services Assessment\"
fileName = Dir(folderpath & "*.xlsx")

Set Wb = Workbooks.Open(fileName)

While fileName <> ""


    Wb.SaveAs , password:="xxxxxxxxxxx"
    Wb.Close

    fileName = Dir
Wend

End Sub

1 个答案:

答案 0 :(得分:0)

正确的循环是:

Sub passwordprotect()

Dim fileName As Variant
Dim Wb As Workbook

    folderpath = "C:\Realty Services Assessment\"
    fileName = Dir(folderpath & "*.xlsx")

    While fileName <> ""

        Set Wb = Workbooks.Open(folderpath & fileName)
        Wb.SaveAs , password:="xxxxxxxxxxx"
        Wb.Close

        fileName = Dir
    Wend

End Sub