0

我一直在努力学习改进此代码的方法并从该站点和其他站点中获取示例-但是我似乎无法克服运行时错误 1004“工作表类的粘贴方法失败”。我有另外两个类似的宏和一个按钮,它将运行所有 3 个。它以相同的语法运行前两个,围绕粘贴到“MyQueue”文件中很好,但第三个它不会粘贴并引发此错误。任何人都可以帮忙吗?

Sub CSQAgentSummaryEdit()

Dim MyPath As String
MyPath = " path "
MyFile = " file "
QueuePath = "path "
MyQueue = " file "
Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = Workbooks.Open(QueuePath)
Set wb2 = Workbooks.Open(MyPath)

Columns("A:V").Delete Shift:=xlUp
Columns("B").Delete Shift:=xlUp
Columns("C:R").Delete Shift:=xlUp


 Range("A1").Select
  Selection.End(xlDown).Select
  ActiveCell.Offset(2, 0).Range("A1").Select
  Selection.consolidate Sources:= _
    "'file data " _
    , Function:=xlSum, LeftColumn:=True

    Range("A1").CurrentRegion.Delete Shift:=xlUp
    Rows("1:1").Delete

    Range("A1").CurrentRegion.Select
    With Selection.Borders
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
    End With

  Selection.Copy
  Workbooks.Open (QueuePath)
  Range("A1").Select
  Selection.End(xlDown).Select
  ActiveCell.Offset(20, 0).Range("A1").Select
  ActiveSheet.Paste , False
  Workbooks(MyQueue).Save
  Workbooks(MyFile).Close False

End Sub
4

3 回答 3

1

您似乎打开了两次 QueuePath 工作簿。

代替

Selection.Copy
Workbooks.Open (QueuePath)
Range("A1").Select

尝试

Selection.Copy
wb2.Sheets("Sheet1").Range("A1").Select

指定您正在使用的工作簿将有助于避免粘贴到错误的工作簿/粘贴错误。

于 2013-02-07T17:04:03.703 回答
0

请记住,Excel 会受到外部影响和自身行为的影响。VBA 通常不是。Active-anything 通常是不可取的。总是更好:

set wsc = Sheets("Copy Sheet")
set wsp = Sheets("Paste Sheet")

..然后指定范围内。

我也总是使用 .PasteSpecial 而不是 .Paste - 它会导致更少的错误并且不依赖于激活工作表,但这实际上是您问题的线索。

所以,这部分:

Selection.Copy
Workbooks.Open()  'I also think you did this twice so it could be removed, but see below
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(20, 0).Range("A1").Select
ActiveSheet.Paste , False

您不需要选择每个单元格,并且作为一个小问题,.Cells(1) 在指定单个单元格时比 .Range("A1") 更容易阅读 - 但两者都有效。只管破产,然后试试这个:

set rngToCopy = Selection
Set wsToPaste = wb2.Sheets("Name of Sheet")  'you don't need this if there's one sheet in the wb
rngToCopy.copy
wsToPaste.Cells(1).End(xlDown).Offset(20, 0).PasteSpecial
Application.CutCopyMode = False
于 2013-02-07T22:08:06.933 回答
0

您需要激活的工作簿可能不是正确的工作簿。检查此链接:Excel VBA pastelink 运行时错误 1004:应用程序定义或对象定义错误

于 2013-02-07T16:54:07.783 回答