为什么下面的代码在只复制一个文件时给我一个错误代码 52?当要复制超过 1 个文件时,不会给我一个问题

问题描述 投票:0回答:0
Sub CopyFilesX()
    Dim sSrcFolder As String, sTgtFolder As String, sFilename As String
    Dim c As Range, rPatterns As Range
    Dim bBad As Boolean

    sSrcFolder = ActiveSheet.Range("G2").Value
    sTgtFolder = ActiveSheet.Range("G5").Value

    Dim lastRow As Long
    lastRow = Range("A1").End(xlDown).Row

    Set rPatterns = ActiveSheet.Range("A2:A" & lastRow).SpecialCells(xlConstants)
    
    For Each c In rPatterns
        sFilename = Dir(sSrcFolder & "\" & "" & c.Text & "*")
        
        If sFilename = "" Then
            c.Interior.ColorIndex = 3
            bBad = True
        Else
            While sFilename <> ""
                FileCopy sSrcFolder & "\" & sFilename, sTgtFolder & "\" & sFilename
                sFilename = Dir()
                c.Interior.ColorIndex = 4
            Wend
        End If
        
    Next c
    
    If bBad Then MsgBox "Some files were not found. " & _
       "These were highlighted for your reference."
End Sub

在调试时,它把我带到

sFilename = Dir(sSrcFolder & "\" & "" & c.Text & "*")
作为问题的根源。当复制多个文件时,它工作得很好。当它只有一个文件要从一个文件夹复制到另一个文件夹时,它会给我一个错误。

excel vba directory file-copying
© www.soinside.com 2019 - 2024. All rights reserved.