问题描述
我想使用 vba 宏将文件和子文件夹列出到 Excel 工作表中。列表正在运行,但最后一个文件夹的最后一个文件移动到列表中实际文件夹的第一个位置。
这是代码:
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
我一直在寻找 for each 循环或“r=r+1”中的问题,但总是得到这个。你能帮我吗?
解决方法
您可以做两件事 1 在 VBA 上对数组中的输出进行排序,然后打印该数组。否则你也可以在excel上对输出进行排序。我会推荐第一个。