VBA:调整代码,打开文件夹中的所有文件以包含所有子文件夹

时间:2018-05-03 13:18:43

标签: vba excel-vba excel

今天你已经用他的第一个问题帮助了这个VBA菜鸟了,我希望你能指出我正确的方向与后续问题:

我目前有一个工作宏,它会按顺序打开文件夹中的所有excel文件,执行一些操作,然后循环到下一个文件,直到没有剩下。

    Sub HunterGatherer()
    Dim SummarySheet As Worksheet
    Dim FolderPath As String
    Dim NRow As Long
    Dim FileName As String
    Dim WorkBk As Workbook
    Dim SourceRange As Range
    Dim DestRange As Range

    ' Create a new workbook and set a variable to the first sheet.
    Set SummarySheet = ThisWorkbook.Worksheets(1)

    ' Modify this folder path to point to the files you want to use.
    FolderPath = "G:\RMS-PQS\01_KPI\2 QA\Product audits\Test Summary Folder\"

    ' NRow keeps track of where to insert new rows in the destination workbook.
    NRow = 2

    ' Call Dir the first time, pointing it to all Excel files in the folder path.
    FileName = Dir(FolderPath & "*.xl*")

    ' Loop until Dir returns an empty string.
    Do While FileName <> ""
        ' Open a workbook in the folder
        Set WorkBk = Workbooks.Open(FolderPath & FileName)

        ' Hyperlink to Audit Report.
        With SummarySheet
        .Hyperlinks.Add Anchor:=.Range("A" & NRow), _
        Address:=FolderPath & FileName, _
        ScreenTip:=FileName, _
        TextToDisplay:=FileName
        End With

        ' .... Adding some formulas and copying some data to a summary sheet ....


        ' Set the source range to be A9 through C9.
        ' Modify this range for your workbooks.
        ' It can span multiple rows.
        Set SourceRange = WorkBk.Sheets("Summary").Range("A1:Y1")

        ' Set the destination range to start at column B and
        ' be the same size as the source range.
        Set DestRange = SummarySheet.Range("B" & NRow)
        Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
           SourceRange.Columns.Count)

        ' Copy over the values from the source to the destination.
        DestRange.Value = SourceRange.Value

        ' Increase NRow so that we know where to copy data next.
        NRow = NRow + DestRange.Rows.Count

        ' Close the source workbook without saving changes.
        WorkBk.Close savechanges:=False

        ' Use Dir to get the next file name.
        FileName = Dir()
    Loop

    ' Call AutoFit on the destination sheet so that all
    ' data is readable.
    SummarySheet.Columns.AutoFit
End Sub

是否可以调整FodlerPath以包含所有子文件夹(及其子文件夹等)?

甚至可以选择只打开名为&#34; 2018&#34;的子文件夹。例如?

我真的已经找到了答案,但是我找到的所有解决方案都是针对宏的,因此我没有认识到如何为我的宏调整解决方案。正如我所说,我是一个菜鸟,但是想要学习。

先谢谢你,祝你有个美好的一天

0 个答案:

没有答案