以第2步类型的方式转置数据?

时间:2019-03-05 21:04:12

标签: excel vba

我有这段代码可以根据数据集范围Data创建一个总体数组。

我想让它转置行块(总是每两行Step -2),然后将下一个块放置为与上次转置后的offset(1)一样。

例如:Rows 2-3将在E1:D134中,rows 4-5将在E135:D169中,依此类推。

此代码过去要做的是将单个数组打印到工作表上并保存下来,但是我将其截短一下以使其打印从E1开始的前两个转置行(仅两列),并且那么下面的下两行将偏移到E:D栏中的下一个可用位置。

Option Explicit
Sub Main()
  Dim wb As Workbook
  Dim Data, Last, Mgr
  Dim i As Long, j As Long, k As Long, a As Long
  Dim Dest As Range
  Set wb = ThisWorkbook
  Set Dest = wb.Sheets("Sheet2").Range("E1")
  With ThisWorkbook.Sheets("Sheet3")
    Data = .Range("ed2", .Range("A" & Rows.Count).End(xlUp))
  End With
  wb.Activate
  Application.ScreenUpdating = False
  For i = 1 To UBound(Data)
    If Data(i, 1) <> Last Then
      If i > 1 Then
        Dest.Select
    End If
      Last = Data(i, 1)
      j = 0
    End If
    a = 0
    For k = 1 To UBound(Data, 2)
      Dest.Offset(a, j) = Data(i, k)
      a = a + 1
    Next
    j = j + 1
  Next
End Sub

如何根据上述代码指定?

1 个答案:

答案 0 :(得分:0)

有多种方法可以实现这一目标。这可能是我最接近您的方法(如果我正确理解了您想要实现的目标),可以尝试

Sub Main()
  Dim wb As Workbook
  Dim Data, Last, Mgr
  Dim Rw As Long, Col As Long
  Dim i As Long, k As Long, j As Long
  Dim Dest As Range, TmpArr As Variant
  Set wb = ThisWorkbook
  Set Dest = wb.Sheets("Sheet2").Range("E1")
  With ThisWorkbook.Sheets("Sheet3")
    Data = .Range("ed2", .Range("A" & Rows.Count).End(xlUp))
  End With


Rw = -1
For i = LBound(Data, 1) To UBound(Data, 1) Step 2
k = 1
If i = UBound(Data) Then k = 0
    For Col = LBound(Data, 2) To UBound(Data, 2)
    Rw = Rw + 1
        For j = 0 To k
        Dest.Offset(Rw, j).Value = Data(i + j, Col)
        Next j
    Next Col
Next i

End Sub