【发布时间】:2023-01-12 05:30:45
【问题描述】:
我正在编写一个宏,它从两个不同的位置获取数据并将其粘贴到模板中,将模板另存为新文件,然后循环返回并重复该过程。该宏适用于一个文件,但在循环时失败。具体来说,计算机找不到文件,认为它已被移动或删除。
这是代码:
'sub 和 dims 被排除以节省空间
'set folder locations
dataFolder = "C:\Location\" 'abbreviated
previousFolder = "C:\Other Location\" 'abbreviated
'set file names
dataFile = Dir(dataFolder & "*.xls*")
previousFile = Dir(previousFolder & "*.xls*")
Do While dataFile <> ""
Set dataWB = Workbooks.Open(dataFolder & dataFile)'this is where the code breaks on looping
'the contents of the loop work fine on the first go so I am excluding them
'Save file to directory
ActiveWorkbook.SaveAs ("C:\Save Location\")
'how I am ending the loop
dataFile = Dir
previousFile = Dir
Loop
结束子`
我希望这已经足够清楚了。更简洁:
dataFile = Dir(dataFolder & "*.xls*")
previousFile = Dir(previousFolder & "*.xls*")
Do While dataFile <> "" 'breaks here after succeeding with first file
'stuff to do
dataFile = Dir
previousFile = Dir
Loop
我期待程序获取源文件夹中的下一个文件并重复该过程,但它却中断说它找不到下一个文件(即使它返回该错误消息中的文件名)。
【问题讨论】:
-
previousFile在做什么?您不能同时迭代 2 个不同的文件夹。这两个文件之间有什么联系,它们的名称相同吗? -
您只能进行一个
Dir()循环,因此使用两个Dir()的嵌套循环无法工作。此外,在使用 Dir() 时,“下一个文件”的概念并未严格定义,因此如果您需要成对的匹配文件,则无法保证。