Excel 通过文件夹中的多个工作簿循环命令

Excel 通过文件夹中的多个工作簿循环命令,excel,for-loop,vba,Excel,For Loop,Vba,背景 首先,我意识到所有这些对于数据库来说都是一项完美的任务,但我目前没有这个选项,我认为在excel中继续这样做是一种很好的学习体验 我有多个工作簿,每个工作簿都包含一个标识号列表,我通过下面的代码输入所需工作簿的名称,然后将该列表导入包含多列数据的主工作簿。然后我运行我的程序,将主要数据集分解成不同的表 问题 是否有一种方法可以对包含文件夹中的每个文件使用for循环,这样我就不必依次标识每个工作簿 Sub Export_Specified_Contractor() Dim list

背景
首先,我意识到所有这些对于数据库来说都是一项完美的任务,但我目前没有这个选项,我认为在excel中继续这样做是一种很好的学习体验

我有多个工作簿,每个工作簿都包含一个标识号列表,我通过下面的代码输入所需工作簿的名称,然后将该列表导入包含多列数据的主工作簿。然后我运行我的程序,将主要数据集分解成不同的表

问题
是否有一种方法可以对包含文件夹中的每个文件使用for循环,这样我就不必依次标识每个工作簿

Sub Export_Specified_Contractor()

    Dim listwb As Workbook, mainwb As Workbook
    Dim fname As String
    Dim sht As Worksheet, oput As Worksheet
    Dim LRow As Long, oLRow As Long
    Dim cprng As Range, orng As Range

    '--> Get the name of the contractor list to be exported
    fname = Application.InputBox("Enter Contractor Name", "Name?")

    Set mainwb = ThisWorkbook

    With Application

    '--> Set contractor list file
    Set listwb = .Workbooks.Open _
    ("C:\Documents and Settings\alistairw\My Documents\Disallowed Items\Contractor Lists\" & fname)
    End With

    Set sht = listwb.Sheets("Sheet1")

    '--> Copy contractor list
    With sht
        LRow = .Range("A" & Rows.Count).End(xlUp).Row
        .Range("A1:A" & LRow).Copy
    End With

    mainwb.Activate

    '--> Create contractor list sheet in main workbook and paste values
    With mainwb
        On Error Resume Next
        Sheets("Sheet2").Delete
        Sheets.Add.Name = "Sheet2"
        Set oput = Sheets("Sheet2")
        With oput
            .Range("A1").PasteSpecial
        End With
    End With

    Call Match_and_Export

    '--> Delete the list workbook and list sheet
    Application.DisplayAlerts = False
    listwb.Close
    oput.Delete
    Application.DisplayAlerts = True
End Sub

在文件夹中循环:

MyPath = "C:\Documents and Settings\alistairw\My Documents\Disallowed Items\Contractor Lists\"
strFilename = Dir(MyPath & "\*.xlsx", vbNormal) 'change to xls if needed

If Len(strFilename) = 0 Then Exit Sub ' exit if no files in folder

Do Until strFilename = ""
    'Your code here
    strFilename = Dir()    
Loop

这应该让你开始这个问题已经被问了很多次了。在过去的几天里,这个问题似乎被问了很多。很抱歉,我花了这么长时间才接受这个问题,却被转移到了另一个项目上。这很好用。