运行时错误1004:Microsoft Excel无法访问该文件

时间:2018-08-13 12:38:41

标签: excel vba

尝试在宏中打开文件以将数据从该文件复制到中央文件(在其中运行宏)时遇到标题错误。检查了路径,一切都很好。宏在打开文件的第11个实例之前已打开并复制了10个文件,但是该错误仅发生在第11个文件上。尝试更改文件访问的位置(通过将第12个文件顺序放置在第10个文件之后),但是发生相同的错误。

将dr_x和fl_x声明为字符串

{{1}}

2 个答案:

答案 0 :(得分:0)

不太确定自己在做什么,但是删除所有SELECTACTIVATE语句会使代码运行更加流畅。

SourceFiles数组包含要打开和复制的所有工作簿的路径。

Public Sub Test()

    Dim TargetFile As Workbook, SourceFiles() As Variant
    Dim tgtLastCell As Range, srcLastCell As Range
    Dim tgtWrkSht As Worksheet, srcWrkSht As Worksheet
    Dim fle As Variant

    Dim wrkBk As Workbook

    SourceFiles = Array("C:\MyPath\Book1.xlsx", _
                        "C:\MyOtherPath\Book2.xlsx")

    Set TargetFile = ThisWorkbook 'If target sheet is in file containing this code.
    'or
    'Set TargetFile = Workbooks.Open("C:\SomePath\Book3.xlsx")

    Set tgtWrkSht = TargetFile.Worksheets("Sheet1")

    For Each fle In SourceFiles
        'Find current last cell in target sheet.
        Set tgtLastCell = LastCell(tgtWrkSht)

        'Open source file, set reference to sheet1 and find the last cell containing data.
        Set wrkBk = Workbooks.Open(fle)
        Set srcWrkSht = wrkBk.Worksheets("Sheet1")
        Set srcLastCell = LastCell(srcWrkSht)

        'Copy & paste contents of sheet on to end of target sheet.
        With srcWrkSht
            .Range(.Cells(1, 1), srcLastCell).Copy Destination:=tgtWrkSht.Cells(tgtLastCell.Row + 1, 1)
        End With

        'Close source workbook.
        wrkBk.Close False
    Next fle

End Sub

Public Function LastCell(wrkSht As Worksheet) As Range

    Dim lLastCol As Long, lLastRow As Long

    On Error Resume Next

    With wrkSht
        lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
        lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row

        If lLastCol = 0 Then lLastCol = 1
        If lLastRow = 0 Then lLastRow = 1

        Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
    End With
    On Error GoTo 0

End Function

答案 1 :(得分:0)

我对上述问题的回答如下-

Sub Consolidate()
Path = "\\Source-Path\"
Filename = Dir(Path & "*.xlsx")
  Do While Filename <> ""
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
     For Each Sheet In ActiveWorkbook.Sheets
     Sheet.Copy After:=ThisWorkbook.Sheets(1)
  Next Sheet
     Workbooks(Filename).Close
     Filename = Dir()
  Loop
End Sub

其中“ \ Source-Path \”是存储所有源文件(从中复制数据)的文件夹。