2017-04-24 46 views
0

我有一个程序需要复制同一工作簿和工作表中的选择列。 当前的代码导致Excel崩溃,所以我不确定它是否工作。如何复制同一工作表中的列Excel VBA

有没有更好的方法来将同一工作表中的列复制到同一个工作簿中?

代码:

Sub Macro1() 

Dim wb1 As Workbook 

'Set it to be the file location, name, and file extension of the Working File 
Set wb1 = Workbooks.Open("Z:\XXX\Working File.xlsx") 

MsgBox "Copying Fields within Working File" 

wb1.Worksheets(1).Columns("G").Copy wb1.Worksheets(1).Columns("H").Value 
wb1.Worksheets(1).Columns("J").Copy wb1.Worksheets(1).Columns("O").Value 
wb1.Worksheets(1).Columns("K").Copy wb1.Worksheets(1).Columns("N").Value 
wb1.Worksheets(1).Columns("M").Copy wb1.Worksheets(1).Columns("P").Value 

wb1.Close SaveChanges:=True 

End Sub 
+0

在结尾处取下'.Value'。你只是想复制到一个范围,而不是Value。但是,如果你只是需要值而不是格式化/ etc,你可以做'Range([Destination Range])。Value = Range([copy range])。Value',即'wb1.Worksheets(1).Columns “H”)。Value = wb1.Worksheets(1).Columns(“G”)。Value'。另外,您是否需要使用整个色谱柱? – BruceWayne

+0

嗯,我补充说,因为客户想要一个粘贴值的唯一选项,我认为这是你如何能做到这一点 –

+0

我确实需要整列 –

回答

3

试试这个,它设置了两个范围值相等,这将保持数据,但没有格式。它应该更快。

Sub Macro1() 
Dim wb1 As Workbook 
'Set it to be the file location, name, and file extension of the Working File 
Set wb1 = Workbooks.Open("Z:\XXX\Working File.xlsx") 

MsgBox "Copying Fields within Working File" 

With wb1.Worksheets(1) 
    .Columns("H").Value = .Columns("G").Value 
    .Columns("O").Value = .Columns("J").Value 
    .Columns("N").Value = .Columns("K").Value 
    .Columns("P").Value = .Columns("M").Value 
End With 

wb1.Close SaveChanges:=True 

End Sub 

注意您使用的是整列,所以它可能会中止,或需要较长的时间。如果你愿意,你可以直接得到每列的最后一行,并用它来缩短被复制的范围。

编辑:如上所述,使用更小的范围可能会更好。这有点更详细,但你应该能够遵循它在做什么:

Sub Macro1() 
Dim wb1 As Workbook 
Dim lastRow As Long 
'Set it to be the file location, name, and file extension of the Working File 
Set wb1 = ActiveWorkbook 

MsgBox "Copying Fields within Working File" 

With wb1.Worksheets(1) 
    lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row 
    .Range("H1:H" & lastRow).Value = .Range("G1:G" & lastRow).Value 

    lastRow = .Cells(.Rows.Count, "J").End(xlUp).Row 
    .Range("O1:O" & lastRow).Value = .Range("J1:J" & lastRow).Value 

    lastRow = .Cells(.Rows.Count, "K").End(xlUp).Row 
    .Range("N1:N" & lastRow).Value = .Range("K1:K" & lastRow).Value 

    lastRow = .Cells(.Rows.Count, "M").End(xlUp).Row 
    .Range("P1:P" & lastRow).Value = .Range("M1:M" & lastRow).Value 
End With 

wb1.Close SaveChanges:=True 

End Sub 
+2

12要去 - 在这里得到一个“接受的答案”,你就会成功! – YowE3K

+0

谢谢! 这工作,像你说的,它花了一点,但它符合客户的需求 –

+1

祝贺布鲁斯! – YowE3K

相关问题