我在以下行继续收到运行时错误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
我应该改变哪一个?
答案 0 :(得分:2)
您的错误几乎肯定是因为您正在使用
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
上的所有单元格。这相当于说&#34;选择位于E 79th St和1st Avenue交叉口以及E 86th St和York交叉点之间的洛杉矶的所有房屋Ave 纽约&#34;。 (不住在美国,我希望这个比喻有意义。)