繁体   English   中英

使用 VBA 自动复制行并将其粘贴为 Excel 中的列

[英]Copy rows and paste them as columns in Excel with VBA automatically

我正在学习使用 VBA 自动复制和粘贴而不覆盖数据。 我设法从行中复制代码并将它们粘贴为行。

现在,我想复制行(以相同的方式),但每次都将它们粘贴为一列。 第一行必须以日期戳(每个月)开头,然后是金额。 这些金额是从 pivot 表中复制的,该表将每月刷新一次。

这是我的书面代码:

Private Sub CommandButton1_Click()

Dim lastrow As Long, ecol As Long

'Stamp from when the data set is (in months)


        If Worksheets("Database").Range("A3").Offset(1, 1) <> "" Then
            Worksheets("Database").Range("A3").End(xlDown).Select
             ActiveCell.Offset(1, 0).FormulaR1C1 = Now
        End If


'To check the last filled line on sheet 'Database_Input'
lastrow = Sheet12.Cells(Rows.Count, 2).End(xlUp).Row

'Copy Paste section
For i = 2 To lastrow
    Sheet12.Cells(i, 2).Copy
        ecol = Sheet14.Cells(3, Columns.Count).End(xlToRight).Offset(0, 1).Column
    ecol = Sheet14.Cells(3, Columns.Count).End
            Sheet12.Paste Destination:=Sheet14.Cells(3, ecol)
Next i

End Sub

它在以下部分不断给我一个错误:

For i = 2 To lastrow
    Sheet12.Cells(i, 2).Copy
        ecol = Sheet14.Cells(3, Columns.Count).End(xlToRight).Offset(0, 1).Column
    ecol = Sheet14.Cells(3, Columns.Count).End
            Sheet12.Paste Destination:=Sheet14.Cells(3, ecol)
Next i

有谁知道如何处理这个问题? 我复制了我的行 --> 行代码并对其进行了编辑。 也许它必须完全不同。

非常感谢!

您想要RangeColumn属性,而不是Columns

此外,您可以直接传输值,这比复制和粘贴效率略高。

我对所需的目的地范围做了一个半受过教育的猜测。

For i = 2 To lastrow
    ecol = Sheet14.Cells(3, Columns.Count).End(xlToleft).Offset(0, 1).Column 'not columns at the end
    Sheet14.Cells(3, ecol).Value = Sheet12.Cells(i, 2).Value
Next i

我什至没有查看您的代码,如果您想要的只是转置数据版本,请将您的数据放入一个数组(range.value 将给出数组)只需使用循环转置然后将其分配给一个新范围. 如果您希望它们包含公式,请使用 range.formula 而不是 value。 一定要关心相对/绝对引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM