在多个文件中运行单个宏时出现错误文件错误

时间:2016-06-02 06:45:39

标签: vba

运行此代码时显示错误的文件名或编号

我已将所有文件存储在“\ C:\ Users \ 20098323 \ Desktop \ EXCL \”

Sub ProcessFiles()
    Dim Filename, Pathname As String
    Dim wb As Workbook

    Pathname = ActiveWorkbook.Path & "\C:\Users\20098323\Desktop\EXCL\"
    Filename = Dir(Pathname & "*.xlsx")
    Do While Filename <> ""
        Set wb = Workbooks.Open(Pathname & Filename)
        DoWork wb
        wb.Close SaveChanges:=True
        Filename = Dir()
    Loop
End Sub

Sub DoWork(wb As Workbook)
    With wb
        'Do your work here
        .Worksheets(1).Range("A1").Value = "Hello World!"
    End With
End Sub

2 个答案:

答案 0 :(得分:0)

ActiveWorkbook.Path &

行删除\和第一个Pathname = ActiveWorkbook.Path & "\C:\Users\20098323\Desktop\EXCL\"
Pathname = "C:\Users\20098323\Desktop\EXCL\"

答案 1 :(得分:0)

ActiveWorkbook.Path & "\C:\Users\20098323\Desktop\EXCL\"

这是你的问题。它将EXCL文件夹的路径追加到当前工作簿的路径。所以你最终会得到像C:\wherever\you\have\your\workbook\C:\Users\20098323\Desktop\EXCL\这样的东西。而是使用

Pathname = "C:\Users\20098323\Desktop\EXCL\"

这是未来的提示:如果它给您一个错误,请按调试按钮,它会显示错误发生的行。然后,您可以将鼠标悬停在变量名称上并查看其当前值。