在Excel VBA上复制粘贴列

一直试图在excel VBA上复制粘贴一段时间,代码无论如何都不起作用

Sub CopyRangeofCellsanotherone() Dim x As Workbook Dim y As Workbook Dim LastRow As Long Dim LastRowToCopy As Long Set x = Workbooks.Open("C:\trabalho da DELL\source.xlsx") Set y = Workbooks.Open("C:\trabalho da DELL\destination.xlsx") LastRowToCopy = x.Sheets("sourcesheet").Cells(x.Sheets("sourcesheet").Rows.Count, "A").End(xlUp).Row x.Sheets("sourcesheet").Range("A" & LastRowToCopy).Copy 'copy from A1 to lastrow LastRow = y.Sheets("destsheet").Cells(y.Sheets("destsheet").Rows.Count, "A").End(xlUp).Row 'find the last row y.Sheets("destsheet").Range("A" & LastRow).PasteSpecial 'paste on the lastrow of destination + 1 (so next empty row) x.Close End Sub 

我认为代码主要是不言自明的(或至less,我打算这么做),但它不工作! 我怎样才能从列A – 源表中复制内容到列A – 目标表单? 那么我怎样才能把它应用到一组列呢? (从A到G)。 我有5小时的VBA下我的皮带,所以这可能看起来很简单,你们中的一些人…编辑:忘记提及它给我在LastRowToCopy行的运行时错误91。

尝试下面的代码。

注意你写的东西:

扩展这个来完全引用一个范围不只是一个单元格

  sourceSheet.Range("A1:A" & sourceLastRow) 

在此处添加+ 1以粘贴到下一个可用行

 destSheet.Range("A" & destLastRow + 1) 

为工作表本身设置variables,使代码更具可读性

 Set sourceSheet = sourceBk.Sheets("sourcesheet") 

使用lastRowvariables包含更多描述,以便知道正在引用哪个工作簿和工作表

 sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row 

当然,在顶部有Option Explicit来检查你的variables声明。

完整代码:

 Option Explicit Sub CopyRangeofCellsanotherone() Dim sourceBk As Workbook Dim destBK As Workbook Dim sourceLastRow As Long Dim destLastRow As Long Dim sourceSheet As Worksheet Dim destSheet As Worksheet Set sourceBk = Workbooks.Open("C:\trabalho da DELL\source.xlsx") Set destBK = Workbooks.Open("C:\trabalho da DELL\destination.xlsx") Set sourceSheet = sourceBk.Sheets("sourcesheet") Set destSheet = destBK.Sheets("destsheet") sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row destLastRow = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row 'find the last row sourceSheet.Range("A1:A" & sourceLastRow).Copy 'copy from A1 to lastrow destSheet.Range("A" & destLastRow + 1).PasteSpecial 'paste on the lastrow of destination + 1 (so next empty row) sourceBk.Close End Sub 

扩展复制范围:

有很多方法可以将它扩展到一系列的列(你将需要进一步解释)。

例如,如果事先知道最后一列,例如“C”,则可以修改sourceSheet范围的行,如下所示:

 sourceSheet.Range("A1:C" & sourceLastRow) 

如果你不知道,你可以find最后一列,例如根据Ron De Bruin

  sourceLastCol =sourceSheet.Cells(1,sourceSheet.Columns.Count).End(xlToLeft).Column 

复制源范围的语法将变为

 sourceSheet.Range(sourceSheet.Cells(1, 1), sourceSheet.Cells(sourceLastRow, sourceLastCol)).Copy 
 Sub foo2() Dim x As Workbook Dim y As Workbook Set x = Workbooks.Open("C:\trabalho da DELL\source.xlsx") Set y = Workbooks.Open("C:\trabalho da DELL\destination.xlsx") y.Sheets("destsheet").Range("A:A").Value = x.Sheets("sourcesheet").Range("A:A").Value x.Close End Sub 

检查上面的代码是否成功复制列A.
如果是,则重复该行
y.Sheets(“destsheet”)。Range(“A:A”)。Value = x.Sheets(“sourcesheet”)。Range(“A:A”)。Value
将A列replace为其他列。