excel - 第一次迭代后循环文件夹中的所有文件失败
问题描述
我正在尝试通过一个文件夹中的所有文件循环一个宏。第一次迭代后,我收到错误“无效的过程调用或参数”。这可能是什么原因造成的?该文件夹包含许多 xlsx 和 csv 文件。宏设置为仅在 xlsx 文件上运行。
Sub Step18LoopAllFilesInAFolder()
folderName = "D:\Users\Desktop\Macro Data\Test"
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)
Call Step17MasterMacro
End With
' go to the next file in the folder
Fname = Dir
Loop
End Sub
解决方案
根据@braX 的建议,我更改为以下内容。奇迹般有效!
Sub Step18LoopAllFilesInAFolder()
Dim FSO As Object
Dim folder As Object
Dim wb As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
folderPath = "D:\Users\Desktop\Macro Data\Test"
Set folder = FSO.GetFolder(folderPath)
For Each wb In folder.Files
If Right(wb.Name, 4) = "xlsx" Then
Set masterWB = Workbooks.Open(wb)
Call Step17MasterMacro
End If
Next
End Sub
推荐阅读
- html - 文本链接背景颜色上的 Outlook 深色模式混乱
- android - 在 Jetpack Compose 中单击按钮时如何更改文本值?
- php - 使用PHP根据物品重量计算运费
- android - 增加两个文本按钮的宽度以填充 sizebox 的空间
- c# - Mathf.Sign(0) 不返回零
- javascript - 如何在 React 中构建部分启用 typescript 的项目
- xv6 - 在 ubuntu 中运行 xv6 时,makefile 出现错误
- c# - 统一进行光线投射时出现 NullReferenceException
- python - 如何添加功能并将其放在周边返回结果?Python
- c++ - 使用带有索引的包扩展 - 是 UB 吗?