【问题标题】:Excel macro erases cell VBAExcel宏擦除单元格VBA
【发布时间】:2017-07-20 14:24:59
【问题描述】:

我正在尝试制作一个 excel 宏,该宏在下一列中列出每个文件夹名称及其所有子文件夹,类似于命令提示符树命令。我期望看到的是这样的:

注意,文件夹 2 4 和 5 中没有文件夹,只有文件,我不希望它显示文件。我已经重新打开屏幕更新,所以我可以看到它做了什么,它确实在正确的位置列出了没有子文件夹的文件夹,但随后立即覆盖了它们,所以我只剩下这个:

这是代码

Sub Example2()
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim i As Integer, j As Integer

    'Create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Get the folder object
    Set objFolder = objFSO.GetFolder("Y:filepath")

    i = 1
    j = 1

    'loops through each file in the directory and prints their names and path
    For Each objSubFolder In objFolder.subfolders
        'print folder name
        Cells(i + 1, 1) = objSubFolder.Name
        'print folder path
        'Cells(i + 1, 2) = objSubFolder.Path

        For Each objsubsubfolder In objSubFolder.subfolders
            Cells(i + 1, j + 1) = objsubsubfolder.Name
            i = i + 1
        Next objsubsubfolder
    Next objSubFolder
End Sub

【问题讨论】:

  • 如果没有子文件夹,您的循环不会增加 i

标签: vba excel directory


【解决方案1】:

正如@SJR 指出的那样:您的循环不会增加 i 如果没有子文件夹。

您需要在该行之前添加一个 i = i + 1

For Each objsubsubfolder In objSubFolder.subfolders

旁注:

  1. Always use Long instead of Integer 尤其是在处理行数时。
    Excel 的行数超出了Integer 的处理能力。

    Dim i As Long, j As Long
    
  2. 您应该为所有Cells 指定一个工作表,例如

    Worksheets("SheetName").Cells
    

    以避免任何问题。永远不要假设工作表。

  3. 如果您设置i = 2 的开头而不是i = 1,则可以使用.Cells(i, …),而不是所有.Cells(i + 1, …),这使得它更易于阅读。

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多