【问题标题】:Looping Issue with VBA Macro in ExcelExcel 中 VBA 宏的循环问题
【发布时间】: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() 时,“下一个文件”的概念并未严格定义,因此如果您需要成对的匹配文件,则无法保证。

标签: excel vba loops


【解决方案1】:

如果将文件循环推到一个单独的函数中,那么处理多个文件位置会更容易:

Sub tester()
    Dim files As Collection, filesPrev As Collection
    
    Set files = MatchedFiles("C:Temp", "*.xls*")
    Set filesPrev = MatchedFiles("C:TempPrevious", "*.xls*")
    
    Debug.Print files.Count, filesPrev.Count
    
    'do something with file names in the collections
    
End Sub

'Return a collection of file paths
Function MatchedFiles(ByVal fldr As String, pattern As String) As Collection
    Dim f
    If Right(fldr, 1) <> "" Then fldr = fldr & ""
    Set MatchedFiles = New Collection
    f = Dir(fldr & pattern)
    Do While Len(f) > 0
        MatchedFiles.Add fldr & f
        f = Dir()
    Loop
End Function

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 2011-10-29
    • 1970-01-01
    • 2014-12-06
    • 2014-03-07
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多