【问题标题】:Transfer data from specific sheet of multiple files to master file将数据从多个文件的特定工作表传输到主文件
【发布时间】:2015-04-25 02:33:00
【问题描述】:

有人可以帮我解决以下问题: 我在“11-12 财年”文件夹中有大约 12 个工作簿。所有 12 个文件都有一个名为“Categorized”的通用工作表。我正在尝试将数据从所有文件的该表传输到文件 YearlyExpense.xlsm,但出现以下错误:

运行时错误 1004。找不到“xxx.xlsx”。检查 名称的拼写,并验证文件位置是否正确。

我的代码如下:

Sub LoopThroughDirectory()

Dim MyFile As String
Dim erow
MyFile = Dir("C:\Users\Winston\Documents\Family Budget\Fiscal Year 11-12\")

Do While Len(MyFile) > 0
    If MyFile = "YearlyExpense.Xlsm" Then
        Exit Sub
    End If

    Workbooks.Open (MyFile) 
      'This is where I'm getting error 1004 vba

    Sheets("Categorized").Select
    Range("B32:V32").Copy
    ActiveWorkbook.Close

    erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    ActiveSheet.Paste Destination:=Worksheets("sheet2").Range(Cells(erow, 1), Cells(erow, 22))

    MyFile = Dir
Loop

结束子

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您需要在初始调用Dir 时表达完整路径 目录列表文件掩码。这只会返回文件名;您需要将其与文件所在文件夹的路径连接起来。处理第一个文件后,您需要再次调用Dir 以获取该文件夹中符合原始文件掩码的下一个文件。

    Sub LoopThroughDirectory()
    
        Dim myFile As String, myPath As String, wb As Workbook
    
        myPath = "C:\Users\Winston\Documents\Family Budget\Fiscal Year 11-12\"
        myFile = Dir(myPath & "\*.xl*")
    
        Do While Len(myFile) > 0
            If LCase(myFile) <> "yearlyexpense.xlsm" Then
    
                Debug.Print myPath & Chr(92) & myFile  'use THIS to open the workbook
                Set wb = Workbooks.Open(myPath & Chr(92) & myFile)
                With wb.Sheets("Categorized")
                    'I'll admit to some confusion here as to what gets copied and to where
                    .Range("B32:V32").Copy _
                        Destination:=ThisWorkbook.Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
                End With
                wb.Close False
                Set wb = Nothing
            End If
            myFile = Dir
        Loop
    
    End Sub
    

    【讨论】:

    • 您好,如前所述,我在指定的路径中有 12 个 excel 文件。现在,目标是将每个文件中从 B32:V32 范围内的行复制到下一个可用空行中的目标文件“yearlyexpense.xlsm”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多