1

我正在尝试将一系列单元格从关闭的工作簿复制到当前工作簿,但我总是得到 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)

感谢您的所有帮助,谢谢!

4

1 回答 1

0

两件事情

  1. 如果说用户取消了对话框,您可能希望在之后退出子程序,MsgBox "No file was selected"以便代码不会在此行中给出错误?Set WBdata = Workbooks.Open(DataFile)或者Else对Statement部分的代码进行处理If如下代码所示

  2. 您收到该错误是因为您没有完全限定单元格,例如请参阅下面代码中.(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
于 2013-02-08T00:03:07.833 回答