Vba 转置拷贝
例如,我的电子表格就像一个[21x4]数组。 现在,我想从上述数组中垂直分离并排列(复制和粘贴)三个[7x4]数组,以获得一个[7 x 12]数组。Vba 转置拷贝,vba,Vba,例如,我的电子表格就像一个[21x4]数组。 现在,我想从上述数组中垂直分离并排列(复制和粘贴)三个[7x4]数组,以获得一个[7 x 12]数组。 任何帮助都将不胜感激。谢谢大家! 请尝试下一个代码。我希望我能理解你在问题中的意思。。。 假设您遵循常规惯例,以行后跟列的形式表示数组: Sub sliceArrayTransposeHoriz() Dim sh As Worksheet, arr, slice, nrRows As Long Dim col As Long, lastRow
任何帮助都将不胜感激。谢谢大家! 请尝试下一个代码。我希望我能理解你在问题中的意思。。。 假设您遵循常规惯例,以行后跟列的形式表示数组:
Sub sliceArrayTransposeHoriz()
Dim sh As Worksheet, arr, slice, nrRows As Long
Dim col As Long, lastRow As Long, i As Long
Set sh = ActiveSheet
nrRows = 7: col = 4: lastRow = 21
arr = sh.Range("A1:D" & lastRow).Value 'put the range in an array
For i = nrRows + 1 To lastRow Step nrRows
'take an array slice of 7 rows and 4 columns:
slice = Application.Index(arr, Application.Evaluate("row(" & i & ":" & _
i + nrRows - 1 & ")"), Array(1, 2, 3, 4))
'drop the slice content in the next empty column:
sh.cells(col + 1).Resize(UBound(slice), UBound(slice, 2)).Value = slice
col = col + 4 'obtain the next last column for the following slice content dropping
Next
'clear the range starting from the 8th row:
sh.Range(sh.cells(nrRows + 1, 1), sh.cells(lastRow, 4)).ClearContents
End Sub
但是,由于您的问题不清楚,至少对我来说,请测试垂直转置的代码版本:
Sub sliceArrayTransposeVert()
Dim sh As Worksheet, arr, slice, nrRows As Long
Dim cols As Long, lastRow As Long, lastCol As Long, i As Long
Set sh = ActiveSheet
nrRows = 7: cols = 4
lastCol = sh.cells(1, Columns.count).End(xlToLeft).Column
arr = sh.Range("A1:L7").Value
For i = cols + 1 To lastCol Step cols
slice = Application.Index(arr, Application.Evaluate("row(1:7)"), _
Application.Transpose(Application.Evaluate("row(" & i & ":" & i + cols - 1 & ")")))
sh.cells(nrRows + 1, 1).Resize(UBound(slice), UBound(slice, 2)).Value = slice ': Stop
nrRows = nrRows + 7
Next
sh.Range(sh.cells(1, cols + 1), sh.cells(7, lastCol)).ClearContents
End Sub
将以下代码放入模块中:
Public Sub SpreadBlocks(ByRef r_src As Range, ByVal n_rows As Long, ByRef r_dst As Range)
Dim n_all_rows As Long, n_cols As Long
n_all_rows = r_src.Worksheet.Range( _
r_src, r_src.End(xlDown)).Rows.Count
n_cols = r_src.Worksheet.Range( _
r_src, r_src.End(xlToRight)).Columns.Count
Dim n_blocks As Long, i As Long
n_blocks = n_all_rows \ n_rows
For i = 1 To n_blocks
r_dst.Offset(0, (i - 1) * n_cols).Resize(n_rows, n_cols).Value2 = _
r_src.Offset((i - 1) * n_rows, 0).Resize(n_rows, n_cols).Value2
Next i
End Sub
以下简称:
Public Sub Test()
SpreadBlocks Range("A2"), 7, Range("F2")
' | | |
' | | +-> Top left cell of destination
' | +----> Number of rows for each block
' +-----------------> Top left cell of source
End Sub
你的意思是像“A1:D21”这样的东西要在“A1:L7”中转换吗?我认为,编辑你的问题并放置两张图片(如果不是可编辑的话)会很好。现有的情况,然后是理想的情况。数组通常以行和列表示。现在,说到“垂直粘贴”,我不明白您想要什么。所以不需要实际的转置操作(将行交换为列)?您只需要将7×4个块从堆叠在一起移动到相邻位置即可。@Tuấ恩古ễn:你能不能抽点时间测试一下上面的代码?你没有回答我的澄清问题,也没有。。。