【问题标题】:Error 1004 -Cannot open file . when I try to open workbooks in a folder错误 1004 - 无法打开文件。当我尝试打开文件夹中的工作簿时
【发布时间】:2015-10-28 22:09:35
【问题描述】:

好的,我正在尝试从一个文件夹中的几个工作簿中提取数据并将它们全部放在一个文件中。当代码点击 Workbooks.Open 时,会弹出错误 1004,我确信文件没有损坏。

Sub Extract_Class_Data()

' Extract_ERP_Class_Data Macro

' Goes into all the files in the folder and extracts the data from each of them.

Dim MyFile As String
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet

Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Sheet1")

Dim erow
Dim Filepath As String
Filepath = ThisWorkbook.Path
MyFile = Dir(Filepath & "\*.xlsx")
Do While Len(MyFile) > 0
If MyFile = "ZZZ.xlsm" Then
Exit Sub
End If

**Workbooks.Open (MyFile)**
Worksheets(Data).Activate
    Range("B6:B12").Select
    Selection.Copy
    ActiveWorkbook.Close savechanges:=False

sourceSheet.Select
ActiveSheet.Paste
Range("B1").Select
ActiveCell.Offset(0, 1).Select
MyFile = Dir

Loop

End Sub

【问题讨论】:

  • DIR 不返回文件名但不返回路径?
  • 相关。您可以查看FileSystemObject 以访问磁盘上的文件。它比dir 使用起来更直接
  • 我应该这样做 MyFile = Dir(FilePath) 吗?

标签: excel vba


【解决方案1】:

这行得通:

Public Sub openaworkbook()
    Dim filen As String, filepath As String, myfile As String
    filen = "temp.xlsx"
    filepath = "c:\temp\"
    myfile = Dir(filepath & filen)
    Workbooks.Open (filepath & myfile)
End Sub

在打开命令中需要文件路径,DIR 不返回路径,只返回文件名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2017-01-22
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多