2014-09-29 87 views
-1

我正在研究一个将从其他工作表信息更新Excel电子表格的宏。但是,更新时我想将两列移到前面,因为我不希望它们改变。一切工作到我将两列移到前面的地步。我选择它们,剪切它们并粘贴它们,但由于某种原因,在粘贴发生后,它会抛出一个错误,指出粘贴失败(错误1004-Range类的PasteSpecial方法失败)。我很困惑,为什么会发生这种情况,任何帮助将不胜感激。Excel更新宏

Sub crossUpdate() 

Dim rng1 As Range, rng2 As Range, rng1Row As Range, rng2Row As Range, Key As Range, match As Integer 
Dim wb1 As Workbook 
Dim wb2 As Workbook 

Set wb1 = Workbooks("011 High Level Task List v2.xlsm") 
Set wb2 = Workbooks("011 High Level Task List v2 ESI.xlsm") 

'Unfilter and Unhide both sheets 
With wb1.Sheets("Development Priority List") 
.Cells.EntireColumn.Hidden = False 
.Cells.EntireRow.Hidden = False 
.AutoFilterMode = False 
End With 
With wb2.Sheets("Development Priority List") 
.Cells.EntireColumn.Hidden = False 
.Cells.EntireRow.Hidden = False 
.AutoFilterMode = False 
End With 

'Copy and paste original sheet to new temp sheet 
wb1.Sheets("Development Priority List").Activate 
wb1.Sheets("Development Priority List").Cells.Select 
Selection.Copy 
Sheets.Add.Name = "SourceData" 
wb1.Sheets("SourceData").Paste 

'Sort temp sheet by key 
N = Cells(Rows.Count, "A").End(xlUp).Row 
Set rng1 = wb1.Sheets("SourceData").Cells.Range("A2:A" & N) 
Set rng1Row = rng1.EntireRow 
rng1Row.Sort Key1:=Sheets("SourceData").Range("A1") 

'Update sheet sorted by key 
N = Cells(Rows.Count, "A").End(xlUp).Row 
Set rng2 = wb2.Sheets("Development Priority List").Cells.Range("A2:A" & N) 
Set rng2Row = rng2.EntireRow 
rng2Row.Sort Key1:=wb2.Sheets("Development Priority List").Range("A1") 

'Dev columns moved on update sheet 
With wb2.Sheets("Development Priority List") 
.Columns("F:G").Cut 
.Columns("A:B").Insert Shift:=xlToRight 
.Activate 
.Columns("A:B").Select 
End With 
Selection.PasteSpecial  <------ Line that throws error 
End Sub 
+3

这已经回答了你的帖子中的另一个。回去看看它。当你做。激活你会失去你的选择/剪贴板。 – Sorceri 2014-09-29 16:37:10

+0

所以我只是删除.activate? – 2014-09-29 16:39:30

+0

在.Insert行之后,添加一行如下:.Columns(“A:B”)。复制这应该可以解决您的问题。请参阅此问题中的答案(其中之一):http://stackoverflow.com/questions/26065376/vba-copy-and-paste-macro – Daniel 2014-09-29 16:58:39

回答

0

更改您的代码块这样:

With wb2.Sheets("Development Priority List") 
    .Columns("A:B").Insert Shift:=xlToRight 
    .Columns("H:I").Cut 
    .Range("A1").PasteSpecial 
End With