Excel-VBA - 如果将新文件夹添加到路径,则在Sheet中添加具有新文件夹名称的新行

时间:2017-11-03 15:06:08

标签: windows vba excel-vba ms-office excel

我使用一个宏,它从路径中读取文件夹名称,并将文件夹名称合并到Excel工作表中。这是代码:

Sub Example1()
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim i As Integer

    Application.ScreenUpdating = False
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFolder = objFSO.GetFolder("Path")
    i = 13

    For Each objSubFolder In objFolder.subfolders

        Cells(i + 1, 1) = objSubFolder.Name
        i = i + 1
    Next objSubFolder
    Application.ScreenUpdating = True
End Sub

我想知道的是:如果我添加一个新文件夹并因此添加新名称,是否可以在我的Excel工作表中使用此新文件夹名称插入一个新行在“A”栏中?

这是两个截图,以澄清我的问题: No.1:Baseline No.2:After adding a new folder

正如您所看到的,如果在条目“AUTOSAR”旁边的单元格中写入内容并添加名为“ABBA”的文件夹并让代码再次运行,则链接到“AUTOSAR”的文本,现在紧挨着“ABBA”。这就是为什么我需要代码在路径中添加新文件夹时插入新行。

2 个答案:

答案 0 :(得分:0)

更改此类代码

   For Each objSubFolder In objFolder.subfolders

        Range("a" & Rows.Count).End(xlUp)(2) = objSubFolder.Name

    Next objSubFolder

答案 1 :(得分:-1)

以下是答案:

Sub Example1()
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim lngNext As Long

Application.ScreenUpdating = False
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFolder = objFSO.GetFolder("Path")

lngNext = Application.Max(14, Cells(Rows.Count, 1).End(xlUp).Row + 1)

For Each objSubFolder In objFolder.SubFolders
  If IsError(Application.Match(objSubFolder.Name, Columns(1), 0)) Then
    Cells(lngNext, 1) = objSubFolder.Name
    lngNext = lngNext + 1
  End If
Next objSubFolder

Application.ScreenUpdating = True

Set objSubFolder = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
End Sub