粘贴给出"对象需要"错误

时间:2014-05-22 23:53:46

标签: database vba

我收到此错误:

  

错误424:需要对象

在这一行:

ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 1))

在下面的代码中。为什么呢?

    Sub LoopThroughDirectory()

    Dim MyFile As String
    Dim erow
    Dim Filepath As String
    Filepath = "C:\Users\Julio Jesus Sanchez\Desktop\MRSK TXT\"
    MyFile = Dir("C:\Users\Julio Jesus Sanchez\Desktop\MRSK TXT\")

    Do While Len(MyFile) > 0
    If MyFile = "MRSK DATABASE.xlsm" Then
    Exit Sub
    End If

    Workbooks.Open (Filepath & MyFile)
    Range("A1:K1").Copy
    ActiveWorkbook.Close

    erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 1))

    MyFile = Dir

    Loop

    End Sub

1 个答案:

答案 0 :(得分:2)

您关闭ActiveWorkbook,然后引用ActiveSheetActiveSheet是什么意思?如果它是您所引用的主书,那么您应该明确告诉它,通过将其设置为对象,也是MS Access模块​​或Excel中的VBA?您刚刚将其标记为DatabaseVBA,我猜Excel是因为您没有对Excel对象的任何引用。

Dim sh as Worksheet

Set sh = Workbooks("NameOfWorkBook.xlsx").WorkSheets("WorksheetName")

然后,只要您参考表格:

sh.Paste Destination:=sh.Range(Cells(erow, 1), Cells(erow, 1))