我有一张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
问题在于它将复制的选择覆盖到相同的范围。
答案 0 :(得分:4)
最简单,最快的方法是使用数组。我假设以下
A1
至E15
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
答案 1 :(得分:1)
这是我使用的一个子,我已经修改过来做你正在寻找的东西。它将内容转储到名为“数据”的工作表中,将其更改为您希望将其添加到的工作表。
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