运行时错误1004 VBA

时间:2015-07-31 16:20:40

标签: excel-vba vba excel

我有一些VBA代码给了我"运行时错误1004:Range类的PasteSpecial方法失败。"

这是我的代码:

Sub CurrentToOld()
rownumber = ThisWorkbook.Sheets("As-Built Emergency").Range("A1", Worksheets("As-Built Emergency").Range("A2").End(xlDown)).Rows.Count
ThisWorkbook.Sheets("As-Built Emergency").Activate
ThisWorkbook.ActiveSheet.Rows("2:" & rownumber).Select
Selection.Cut
ThisWorkbook.Sheets("OLD AB EMERGENCY").Activate
ThisWorkbook.ActiveSheet.Range("A2").Select
ThisWorkbook.ActiveSheet.Range("A2").PasteSpecial Paste:=xlPasteSpecial, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub

错误是在倒数第二行,我似乎无法弄清楚原因。我复制了大约150行,并且在任何复制的单元中都没有合并的单元格。

我尝试删除.Select语句,然后将我从Rows(" 2:"& rownumber)复制的内容更改为Range(" A1:D4" )[存在的小东西]但我仍然得到错误。

编辑:我把这行:

ThisWorkbook.ActiveSheet.Range("A2").Select

因为我想测试它是否与我编写PasteSpecial代码的方式有关,或者我是否真的需要声明任何内容。

但是当我在调试器中对它进行测试时,上述说法是有效的,所以我在这里停滞不前。

3 个答案:

答案 0 :(得分:0)

尝试激活该范围。

ThisWorkbook.ActiveSheet.Range("A2").Activate

或尝试声明工作表

Sub CurrentToOld()
Dim wb      As Workbook
Set WorkBk = ActiveWorkbook
rownumber = WorkBk.Sheets("As-Built Emergency").Range("A1", Worksheets("As-Built Emergency").Range("A2").End(xlDown)).Rows.Count
WorkBk.Sheets("As-Built Emergency").Activate
WorkBk.ActiveSheet.Rows("2:" & rownumber).Select
Selection.Cut
WorkBk.Sheets("OLD AB EMERGENCY").Activate
WorkBk.ActiveSheet.Range("A2").Select
WorkBk.ActiveSheet.Range("A2").PasteSpecial Paste:=xlPasteSpecial, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub

或者宣布工作表

Sub CurrentToOld()

Dim wb      As Workbook
Set WorkBk = ActiveWorkbook
Dim ws As Excel.Worksheet
Set ws = Application.ActiveSheet

rownumber = WorkBk.Sheets("As-Built Emergency").Range("A1", Worksheets("As-Built Emergency").Range("A2").End(xlDown)).Rows.Count
WorkBk.Sheets("As-Built Emergency").Activate
ws.Rows("2:" & rownumber).Select
Selection.Cut
WorkBk.Sheets("OLD AB EMERGENCY").Activate
ws.Range("A2").Select
ws.Range("A2").PasteSpecial Paste:=xlPasteSpecial, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub

答案 1 :(得分:0)

Sub CurrentToOld()
Dim rownumber As Long
rownumber = ThisWorkbook.Sheets("As-Built Emergency").Range("A1", Worksheets("As-Built Emergency").Range("A2").End(xlDown).Address).Rows.Count
ThisWorkbook.Sheets("As-Built Emergency").Activate
ThisWorkbook.ActiveSheet.Rows("2:" & rownumber).Select
Selection.Cut
ThisWorkbook.Sheets("OLD AB EMERGENCY").Select
ThisWorkbook.Sheets("OLD AB EMERGENCY").Range("A1").Select
ActiveSheet.Paste
End Sub

答案 2 :(得分:0)

显然问题是我发布的表单有数据,我需要先清除用过的单元格。