我正在尝试将一系列单元格从已关闭的工作簿复制到当前的工作簿,但我总是得到ERROR 1004.我使用的代码如下:
Sub Sheet2()
Dim Filt As String
Dim FilterIndex As Integer
Dim Title As String
Dim Multi As Boolean
Dim DataFile
Dim WBdata As Workbook
'I prompt the user to select the file to import
Filt = "Excel Workbook 2010 (*.xlsx),*.xlsx," & "Excel Workbook (*.xls), *.xls," & "All Files (*.*),*.*"
FilterIndex = 1
Title = "Select file to import"
Multi = False
DataFile = Application.GetOpenFilename(FileFilter:=Filt, FilterIndex:=FilterIndex, Title:=Title, MultiSelect:=Multi)
If DataFile = False Then
MsgBox "No file was selected"
End If
'Open the file selected by the user
Set WBdata = Workbooks.Open(DataFile)
'Get the data
WBdata.Activate
Sheets("Sheet1").Range(Cells(4, 1), Cells(4, 1).End(xlDown).Offset(-1, 0)).Copy _ ThisWorkbook.Sheets("Sheet2").Columns(1)
ThisWorkbook.Sheets("Sheet2").Activate
ThisWorkbook.Sheets("Sheet2").Columns(1).Select
Selection.EntireColumn.AutoFit
'Close and Select Cell (1,1)
WBdata.Close
ThisWorkbook.Sheets("Manager").Activate
ThisWorkbook.Sheets("Manager").Cells(1, 1).Select
End Sub
调试器在Sheets("Sheet1").Range(Cells(4, 1), Cells(4, 1).End(xlDown).Offset(-1, 0)).Copy _ ThisWorkbook.Sheets("Sheet2").Columns(1)
停止。
我在测试文件中尝试了相同的语法,但它很顺利,但我无法在实际文件中实现。这是测试文件中的代码:
Sheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlDown).Offset(-1, 0)).Copy ThisWorkbook.Sheets("Sheet1").Columns(2)
感谢您的帮助,谢谢!
答案 0 :(得分:0)
两件事
您可能希望在MsgBox "No file was selected"
之后退出该子代码,以便代码在此行Set WBdata = Workbooks.Open(DataFile)
中没有给出错误,如果用户取消了该对话框的话?或者处理Else
声明的If
部分中的代码,如下面的代码所示
您收到该错误是因为您尚未完全限定单元格,例如,请参阅以下代码中的.(DOT)
中的Cells(1, 1)
您的代码可以重写为( UNTESTED )
Sub Sheet2()
Dim Filt As String, Title As String
Dim FilterIndex As Integer
Dim Multi As Boolean
Dim DataFile
Dim WBdata As Workbook, ws As Worksheet
Filt = "Excel Workbook 2010 (*.xlsx),*.xlsx," & _
"Excel Workbook (*.xls), *.xls," & _
"All Files (*.*),*.*"
FilterIndex = 1
Title = "Select file to import"
Multi = False
DataFile = Application.GetOpenFilename(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title, _
MultiSelect:=Multi)
If DataFile = False Then
MsgBox "No file was selected"
Else
'Open the file selected by the user
Set WBdata = Workbooks.Open(DataFile)
Set ws = WBdata.Sheets("Sheet2")
'Get the data
With ws
.Range(.Cells(4, 1), .Cells(4, 1).End(xlDown).Offset(-1, 0)).Copy _
ThisWorkbook.Sheets("Sheet2").Columns(1)
ThisWorkbook.Sheets("Sheet2").Columns(1).EntireColumn.AutoFit
'Close and Select Cell (1,1)
WBdata.Close SaveChanges:=False
End With
End If
End Sub