首页 > 解决方案 > 文件目录不返回任何对象

问题描述

我需要遍历文件夹中的 Excel 文件并擦除封面上的单元格 A1。我在 Stackoverflow 上找到了这段代码。单步执行显示它是第 3 行,文件不返回任何对象。

Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("C:\Users\Usuario\Desktop\BENCHMARKS\2. Scope files")

While (file <> "")
    Debug.Print Sheets("Cover").Cells(1, 1)
    file = Dir
Wend
End Sub

标签: excelvba

解决方案


您需要指定要循环遍历的文件,例如所有 Excel 文件。您需要在循环中打开、编辑和保存它们。

请注意,您需要额外的路径才能打开文件,因为dir只返回没有路径的文件名,但您需要两者都能够打开它。

Option Explicit

Public Sub LoopThroughFiles()
    Dim Path As String
    Path = "C:\Users\Usuario\Desktop\BENCHMARKS\2. Scope files\" 'needs to end with a backslash
    
    Dim FileName As String
    FileName = Dir(Path & "*.xls?") '*.xls? will accept all excel file formals: xls, xlsx, xlsm, xlsb, …

    While FileName <> vbNullString
        Debug.Print Path & FileName 'just to show which file we are currently on (can be removed)
        
        'open the workbook
        Dim OpenWb As Workbook
        Set OpenWb = Application.Workbooks.Open(FileName:=Path & FileName)
        
        'clear A1
        OpenWb.Worksheets("Cover").Cells(1, 1).ClearContents
        
        'save and close
        OpenWb.Close SaveChanges:=True
        
        'next wb
        FileName = Dir
    Loop
End Sub

请注意,这可能会受益于一些尚未包含的正确错误处理。
查看VBA 错误处理 - 完整指南


推荐阅读