0

我下面的代码遇到“需要对象的错误”。你能帮我理解什么是错的吗?

Private Sub Command9_Click()
   Dim sPath As String
   Dim sFil As String
   Dim strName As String
   Dim twbk As Workbook
   Dim owbk As Workbook
   Dim ws As Worksheet

   Set twbk = ActiveWorkbook
   sPath = "C:\Adise\Export\" 'Change to suit
   sFil = Dir(sPath & "*.xls")

   Do While sFil <> ""
      strName = sPath & sFil
      Set owbk = Workbooks.Open(strName)
      Set ws = owbk.Sheets(1)
      ws.Range("A1", Range("A" & Row.Count).End(xlUp)).Copy
      twbk.Sheets(1).Range("A65536").End(xlUp)(2).PasteSpecial xlPasteValues
      owbk.Close False 'Close no save
      sFil = Dir
   Loop

   twbk.Save
End Sub
4

2 回答 2

0

试试下面的代码:

这条线的问题:ws.Range("A1", Range("A" & Row.Count).End(xlUp)).Copy

您可以使用查找最后一行Range("A65000").End(xlUp).Row

或者,您可以使用Range("A1").CurrentRegion包含整个当前区域。

Private Sub Command9_Click()
    Dim sPath As String
    Dim sFil As String
    Dim strName As String
    Dim twbk As Workbook
    Dim owbk As Workbook
    Dim ws As Worksheet

    Set twbk = ActiveWorkbook
    sPath = "C:\Adise\Export\"    'Change to suit
    sFil = Dir(sPath & "*.xls")

    Do While sFil <> ""
        strName = sPath & sFil
        Set owbk = Workbooks.Open(strName)
        Set ws = owbk.Sheets(1)
        ws.Range("A1", Range("A" & Range("A65000").End(xlUp).Row)).Copy twbk.Sheets(1).Range("A65536").End(xlUp)
        owbk.Close False    'Close no save
        sFil = Dir
    Loop

    twbk.Save
End Sub
于 2013-03-10T06:09:48.187 回答
0

它应该是复数 - Rows,而不是 Row。:

ws.Range("A1", ws.Range("A" & ws.Rows.Count).End(xlUp)).Copy

Rows.Count返回工作表中的行数:Excel 2003 及更早版本为 65536,Excel 2007 及更高版本为 1,048,576。因此,您还应该将下一行更改为:

twbk.Sheets(1).Range("A" & twbk.Sheets(1).Rows.Count).End(xlUp)(2).PasteSpecial xlPasteValues

如上所述,您还应该限定Rangeswith 。ws

于 2013-03-10T06:38:25.623 回答