简体   繁体   English

Excel VBA - Range.Copy 转置粘贴

[英]Excel VBA - Range.Copy transpose paste

I am following the help menu for PasteSpecial but I cannot seem to get my code to work without an error.我正在关注PasteSpecial的帮助菜单,但我似乎无法让我的代码在没有错误的情况下正常工作。

I want to take Worksheets("Sheet1").Range("A1","A5") and paste transpose to Worksheets("Sheet2").Range("A1","E1") .我想使用Worksheets("Sheet1").Range("A1","A5")并将转置粘贴到Worksheets("Sheet2").Range("A1","E1")

What is the most simple way to accomplish this?完成此任务的最简单方法是什么?

Worksheets("Sheet1").Range("A1:A5").Copy
Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True

Here's an efficient option that doesn't use the clipboard.这是一个不使用剪贴板的有效选项。

Sub transposeAndPasteRow(rowToCopy As Range, pasteTarget As Range)
    pasteTarget.Resize(rowToCopy.Columns.Count) = Application.WorksheetFunction.Transpose(rowToCopy.Value)
End Sub

Use it like this.像这样使用它。

Sub test()
    Call transposeAndPasteRow(Worksheets("Sheet1").Range("A1:A5"), Worksheets("Sheet2").Range("A1"))
End Sub

WorksheetFunction Transpose()工作表函数转置()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula无需通过 PasteSpecial 进行复制、粘贴和使用Transpose选项,您只需键入一个公式

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:或者如果您更喜欢 VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note : alternatively you could use late-bound Application.Transpose instead.注意或者您可以使用后期绑定的Application.Transpose代替。

MS help reference states that having a current version of Microsoft 365 , one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it. MS 帮助参考指出,拥有当前版本的Microsoft 365 ,可以简单地在目标范围的左上角单元格中输入公式,否则必须通过Ctrl+Shift+Enter将公式作为旧数组公式输入以确认它。

Versions Excel vers.版本Excel 版本。 2007+, Mac since 2011, Excel for Microsoft 365 2007 年以上,自 2011 年以来的 Mac,Microsoft 365 的 Excel

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

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