有人可以帮我解决以下问题: 我在“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
End Sub
答案 0 :(得分:0)
您需要在初始调用Dir
时表达完整路径和目录列表文件掩码。这只会返回文件名;您需要将其与文件所在文件夹的路径连接起来。处理完第一个文件后,需要再次调用Dir
以获取该文件夹中符合原始文件掩码的下一个文件。 / p>
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