Excel:如何将具有不同长度的单个列复制到新选项卡中?

时间:2014-06-30 23:26:38

标签: excel vba

我是宏观写作中的另一个新手......这就是我想要做的事情:

将某些列从一张纸复制到另一张纸中,长度或行可能会有所不同。好像很简单吧?但我似乎无法得到它。

Dim RowS01Max As Integer
Dim Sheet1Data() As Variant

With Sheets("sheet1")
  RowS01Max = .Cells(Rows.Count, "A").End(xlUp)
  Sheet1Data = .Range(.Cells(2, 1), .Cells(RowS01Max, 1)).Value
End With

With Sheets("Sheet2")
  .Range(.Cells(2, 5), .Cells(RowS01Max, 5)).Value = Sheet1Data
End With

如果我只想复制一列(“A”),那么这是有效的,如何扩展范围,我相信这是一个简单的解决方法?

任何提示都表示赞赏。

干杯

桑德拉

2 个答案:

答案 0 :(得分:1)

这是我使用一些变量的代码片段。我通常会计算我有多少行才能复制到行大小。

我有这样的事情:

Set Compiled = Sheets("Compiled Sheet")
Set Cycle = Sheets("Cycle Sheet")

countNum = Application.CountA(Range("A:A")) ' Counts how many rows you have

CompileHeader = Compiled.Range("CD1").Value  ' Copies header title.

Compiled.Range("CD2:CD" & countNum).Value = Cycle.Range(ColumnLetter & "2:" & ColumnLetter & countNum).Value

所以在上面的代码中我将列CD(我知道,我的项目中有很多列)复制到“Cycle Sheet”中,设置为“Cycle”。很高兴将表单设置为不必下来并稍后重命名所有代码,因为这往往是一个动态值。

答案 1 :(得分:1)

Excel工作表的有用属性是UsedRange:这将返回一个VBA范围对象,表示指定工作表中包含数据的区域。了解一张表的VBA代号也很方便,这在this article中已经很清楚地解释了。
考虑到这一点,我们可以使用Intersect函数计算表示给定列(或列)中使用过的单元格的范围,然后将其复制到我们选择的目标位置。

Dim rng As Range
Set rng = Intersect(Sheet1.Usedrange, Sheet1.Range("A:A"))

rng.Copy Destination:=Sheet2.Range("B5")

希望这有帮助!