1

我有一个看起来像这样的 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

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

4

2 回答 2

4

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

  1. 数据在 Sheet1 从范围A1E15
  2. 您想要 Sheet2 Cell 中的输出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
于 2012-12-22T05:28:13.750 回答
2

这是我使用的一个子,我已经修改它来做你正在寻找的东西。它将内容转储到名为“数据”的工作表中,将其更改为您希望将其添加到的任何工作表。

Sub Transform()

Dim rows As Long
Dim cols As Long
Dim r As Long
Dim c As Long
Dim t As Long

t = 1
rows = ActiveSheet.UsedRange.rows.Count
cols = ActiveSheet.UsedRange.Columns.Count

Application.ScreenUpdating = False

For r = 1 To rows 'If you have headers change 1 to the first row number of data
    For c = 1 To cols

        Sheets("Data").Cells(t, 1) = ActiveSheet.Cells(r, c).Value

        t = t + 1
    Next c
Next r


Application.ScreenUpdating = True

End Sub
于 2012-12-22T01:36:36.363 回答