gpt4 book ai didi

Excel VBA : copy table as a single column

转载 作者:行者123 更新时间:2023-12-04 21:17:16 25 4
gpt4 key购买 nike

我有一个看起来像这样的 excel 表

data1 data2 data3 ... data10
... ... ... ... ...
dataX dataY dataZ ... dataN

我需要将数据“展平”成一列,如下所示:
data1
data2
data3
...
data10
dataX
dataY
dataZ
...
dataN

我尝试创建一个宏,该宏将从选择开始自动执行复制+粘贴过程。这是我的代码:
Sub copyIn1Col()
'
' copyIn1Col Macro
'
' Keyboard Shortcut: Ctrl+r
'
Selection.copy
Range("B31").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("D3:D13").Select
End Sub

问题在于它将复制的选择覆盖到相同的范围。

最佳答案

最简单和最快的方法是使用数组。我假设以下

  • 数据在 Sheet1 中,范围为 A1E15
  • 您想要 Sheet2 单元格中的输出 A1

  • 希望这是你想要的?
    Option Explicit

    Sub Sample()
    Dim inPutR, outPut()
    Dim i As Long, j As Long, n As Long

    '~~> Change this to the respective range
    inPutR = ThisWorkbook.Sheets("Sheet1").Range("A1:E15")

    ReDim Preserve outPut(UBound(inPutR, 1) * UBound(inPutR, 2))

    For i = LBound(inPutR, 1) To UBound(inPutR, 1)
    For j = LBound(inPutR, 2) To UBound(inPutR, 2)
    outPut(n) = inPutR(i, j)
    n = n + 1
    Next j
    Next i

    ThisWorkbook.Sheets("Sheet2").Range("A1").Resize(UBound(outPut) + 1) = _
    Application.Transpose(outPut)
    End Sub

    关于Excel VBA : copy table as a single column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999227/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com