运行时错误'1004':对象'_worksheet'的方法'Range'在合并时失败

时间:2017-03-28 11:15:17

标签: vba excel-vba excel

class Foo {
    static let classInit : () = {
        // do your global initialization here
    }()

    init() {
        // just reference it so that the variable is initialized
        Foo.classInit
    }
}

运行合并代码时出现以下错误:

  

运行时错误'1004':对象'_worksheet'的方法'范围'失败

1 个答案:

答案 0 :(得分:0)

以下代码是您的代码。然而,我让它变得更加冗长。这可能会让您知道错误的位置:

Option Explicit

Public Sub Compile_Workbook_Data()

Dim master_wkbk As Workbook
Dim master_sht As Worksheet
Dim current_wkbk As Workbook
Dim current_sht As Worksheet
Dim wkbk_list(1 To 3) As String
Dim x As Integer
Dim last_row As Integer
Dim last_col As Integer

Dim bolFound As Boolean
Dim strFilePath As String
Dim strSheetName As String
Dim FSO As New FileSystemObject

Set master_wkbk = ThisWorkbook
strSheetName = "Task Tracking-Internal & Org."
strFilePath = "E:\Delta Dental\"

bolFound = False
For Each master_sht In master_wkbk.Worksheets
    If master_sht.Name = strSheetName Then bolFound = True: Exit For
Next master_sht
If bolFound = False Then MsgBox "Couldn't find the required sheet in this Excel file." & Chr(10) & "Aborting...": Exit Sub

wkbk_list(1) = "Sub Project_WorkBook - Core Services.xlsm"
wkbk_list(2) = "Sub Project_WorkBook - ESP2.0.xlsm"
wkbk_list(3) = "Sub Project_WorkBook - P2E.xlsm"

If Not FSO.DriveExists(Split(strFilePath, "\")(0)) Then MsgBox "Couldn't find the required drive" & Split(strFilePath, "\")(0) & "." & Chr(10) & "Aborting...": Exit Sub
If Not FSO.FolderExists(strFilePath) Then MsgBox "Couldn't find the required folder." & Chr(10) & "Aborting...": Exit Sub

For x = 1 To UBound(wkbk_list)

    If Dir(strFilePath & wkbk_list(x)) = vbNullString Then MsgBox "File " & Chr(10) & "   " & strFilePath & wkbk_list(x) & Chr(10) & "not found." & Chr(10) & "Aborting...": Exit Sub

    Set current_wkbk = Workbooks.Open("D:\Delta Dental\" & wkbk_list(x))

    bolFound = False
    For Each current_sht In current_wkbk.Worksheets
        If current_sht.Name = strSheetName Then bolFound = True: Exit For
    Next current_sht
    If bolFound = False Then MsgBox "Couldn't find the required sheet in the file:" & Chr(10) & "   " & strFilePath & wkbk_list(x) & Chr(10) & "Aborting...": Exit Sub

    last_row = current_sht.Cells.Find("*", searchorder:=xlByRows, SearchDirection:=xlPrevious).Row
    last_col = current_sht.Cells.Find("*", searchorder:=xlByColumns, SearchDirection:=xlPrevious).Column

    current_sht.Range(Cells(4, 1), Cells(last_row, last_col)).Copy

    last_row = master_sht.Cells.Find("*", searchorder:=xlByRows, SearchDirection:=xlPrevious).Row
    master_sht.Range("A" & last_row + 1).PasteSpecial Paste:=xlPasteValues

    current_wkbk.Close False
Next x

End Sub

请注意,上述代码需要引用 Microsoft Scripting Runtime 。请确保在运行代码之前进行设置。

enter image description here