excel - 文件目录不返回任何对象
问题描述
我需要遍历文件夹中的 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
解决方案
您需要指定要循环遍历的文件,例如所有 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 错误处理 - 完整指南。
推荐阅读
- php - 使用 domdocument 查找具有特定类名的所有 HREF
- android - 尝试为颤振应用程序生成 APK,但以下错误不断出现
- c# - Unity 2D:Rigidbody2D.velocity 不移动角色
- flutter - 如何从不同的类更改有状态小部件类中的值?
- python - 带有不起作用的 if 语句的 Python 嵌套理解
- swift - 洗牌随机的问题在哪里
- corda - 如何调试corda流测试中的类星体错误?
- python - 在 C 中子类化 Python 类
- oracle - 显示项目中的 oracle 表单隐藏字段
- kubernetes - 有没有办法从 Argo CD API 获取 sha256 图像摘要?