簡體   English   中英

運行時錯誤1004:Excel VBA

[英]runtime error 1004 : excel VBA

我不斷在以下行上收到運行時錯誤1004:

originBook.Sheets(1).Range(Cells(1, 1), Cells(lastRow, lastCol)).Copy

這是完整的代碼

Sub Obtain_Source()

    Application.DisplayAlerts = False

    Dim theOrigin, theString, newCol As String
    Dim lastRow, lastCol As Long
    Dim theRange As Range
    Dim originBook, originBookBackup, macroBook As Workbook
    Dim originOpen As Boolean

    originOpen = False

    Set macroBook = Workbooks("FY_Macro_Testt (DYNAMIC).xlsm")

    theOrigin = Application.GetOpenFilename(fileFilter:="Excel Files (*.xls; *.xlsm; *.xlsx), *.xls' *.xlsm' *.xlsx", _
    Title:="Fiscal Year Selection: Select Only One", ButtonText:="Open", MultiSelect:=False)

    If TypeName(theOrigin) = "Boolean" Then
        MsgBox "Don't just stand there.  Do something." & vbNewLine & _
               "Quit hitting CANCEL.  >.< ", vbExclamation, "WARNING.  CHOKING HAZARD."
    Else
        originOpen = True
        Set originBook = Workbooks.Open(theOrigin)
            lastRow = Range("A65536").End(xlUp).Row
            lastCol = Range("XFD1").End(xlToLeft).Column
            lastCol = originBook.Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column

        originBook.Sheets(2).Visible = False
        originBook.Sheets(3).Visible = False

        originBook.Sheets(1).Range(Cells(1, 1), Cells(lastRow, lastCol)).Copy
        macroBook.Sheets(1).Cells(6, 1).PasteSpecial
        i = 1000
       Do While 1000 <= 20000
           j = i - 999
            If originBook.Sheets(1).Cells(i, 1).Value <> vbNullString Or _
               originBook.Sheets(1).Cells(i, 1).Value <> "" Then
                originBook.Sheets(1).Range(Cells(j, 1), Cells(i - 1, lastCol)).Copy
               macroBook.Sheets(1).Cells(j + 5, 1).PasteSpecial

            End If
           i = i + 1000
        Loop
       originBook.Sheets(2).Visible = True
       originBook.Sheets(3).Visible = True
    End If

    If originOpen = True Then
        originBook.Close
    End If

End Sub

我應該改變哪一個?

您的錯誤幾乎肯定是因為您正在使用

originBook.Sheets(1).Range(Cells(1, 1), Cells(lastRow, lastCol)).Copy

而不是像@ShaiRado所指出的那樣,

originBook.Sheets(1).Range(originBook.Sheets(1).Cells(1, 1), _
                           originBook.Sheets(1).Cells(lastRow, lastCol)).Copy

如果它們不完全合格,則Cells引用將引用ActiveSheet上的單元格。 因此,Excel必須嘗試復制Sheets(1)ActiveSheet上兩個單元格之間區域中的所有單元格。 這相當於說“選擇洛杉磯的所有擺在了E第79街和第一大道的交叉點和E第86街和約克大道紐約的交叉點的區域的房子”。 (我不住在美國,我希望類比是有道理的。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM