【发布时间】:2023-02-02 01:33:30
【问题描述】:
我正在尝试遍历包含不同 csv 文件的文件夹并复制前缀为 AB 的文件。但是,我的循环卡在它找到的第二个文件上,并不断复制和粘贴它。有没有人发现这可能发生在哪里?
Do Until Dir(filepath & "*") = ""
' defining path and file names
abfilename = Dir(filepath & "AB" & "*")
abfilepath = filepath & "AB" & "*"
' if pathname doesnt return files then quit and clear contents
If Len(abfilename) = 0 Then
' ThisWorkbook.Sheets("AB_*").Range("A:Z").ClearContents
MsgBox "The data folder has no SW files"
Exit Sub
' AB files found and copied
ElseIf abfilename <> "" Then
MsgBox "File Found"
' iterate while there are files with SW prefix
While Dir(abfilepath) <> ""
' Copying into worksheet
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
abfilename_stripped = Replace(abfilename, ".csv", "")
Set ws = ThisWorkbook.Sheets(abfilename_stripped)
Workbooks.Open abfilepath, Local:=True ' Open the csv
MsgBox abfilename
Set csv = ActiveWorkbook ' Create object of csv workbook
csv.ActiveSheet.Range("A:Z").Copy ' Copy all cells
MsgBox "File Copied"
ws.Activate ' Go back to pasting sheet
ws.Range("A1").PasteSpecial xlPasteValues 'Pasting Values
MsgBox "File Pasted"
csv.Close ' Closing open csv
Set csv = Nothing
swfilename = Dir()
Wend
End If
【问题讨论】: