简体   繁体   English

为什么最后一个文件是 vba 中的第一个文件?

[英]Why will be the last file the first one in vba for each?

I would like to list the files and subfolders to an Excel sheet with vba macro.我想将文件和子文件夹列出到带有 vba 宏的 Excel 工作表中。 The listing is working, but the last file of last folder moves to first place of actual folder in the list.该列表正在运行,但最后一个文件夹的最后一个文件移动到列表中实际文件夹的第一位。

Here is the result:结果如下: 在此处输入图像描述

And here is the code:这是代码:

If selectedFolder.Files.Count = 0 Then
            For Each origSubFolder In selectedFolder.SubFolders
                'Create backup subfolder
                copiedSubFolder = copiedFilesDir & "\" & origSubFolder.Name & affix
                fso.CreateFolder copiedSubFolder
                
                'Recording folders to Excel file
                rfSht.Range("C" & r).Value = origSubFolder
                rfSht.Range("M" & r).Value = copiedSubFolder
                r = r + 1
                
                For Each File In origSubFolder.Files
                    'Save As original files as xlsx
                    fileName = fso.GetFileName(File)
                    fileNameWOExt = Left(fileName, (InStrRev(fileName, ".", -1, vbTextCompare) - 1))
                        'fileNameWOExt = Left(fileName, InStr(fileName, ".") - 1)
                    fileNameWAffix = fileNameWOExt & affix
                    Set owb = Workbooks.Open(File)
                    owb.SaveAs fileName:=copiedSubFolder & "\" & fileNameWAffix, FileFormat:=51
                    ActiveWorkbook.Close
                    
                    'Recording files to Excel file
                    rfSht.Range("D" & r).Value = File
                    rfSht.Range("N" & r).Value = copiedSubFolder & "\" & fileNameWAffix & ".xlsx"
                    r = r + 1
                Next
            Next
            MsgBox "Task completed", vbInformation
        Else

I was looking for the problem in the for each loop or "r=r+1", but always get this.我在 for each 循环或“r=r+1”中寻找问题,但总是得到这个。 Could you help me?你可以帮帮我吗?

You could do 2 things 1 is sorting the output in an array on VBA and then print the Array.您可以做 2 件事 1 是在 VBA 上的数组中对 output 进行排序,然后打印该数组。 else you could also sort output on excel.否则你也可以在 excel 上对 output 进行排序。 I would recommend the first one.我会推荐第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM