【问题标题】:Transpose with VBA in EXCEL在 EXCEL 中使用 VBA 转置
【发布时间】:2017-11-26 18:12:56
【问题描述】:

我在 Excel 中有一些这样的数据:

1A
1B
1C
2A
2B
2C
3A
3B
3C

我想要这个:

1A 2A 3A
1B 2B 3B
1C 2C 3C

这是我在 VBA 中的公式,但我的数据有误。

Public Sub TransposePaste()


'Value we want to step by
Dim stepVal As Long
stepVal = 3


'Declare start row variable (-1)
Dim row As Long
row = 0

'Declare the column the data is coming from
Dim col As Long
col = 1

'Declare and set worksheet
Dim ws As Worksheet
Set ws = Sheet1

'end row of the data
Dim endRow As Long


endRow = ws.Cells(ws.Rows.Count, col).End(xlUp).row

    'cycle to end of data end of data...
    For i = 1 To endRow Step stepVal

    'increment row each time
    row = row + 1

        'cycle through the columns outputting the data
        For j = 1 To stepVal

        Sheet1.Cells(row, j).Value = Sheet1.Cells(i + j - 1, col).Value

        Next j
    Next i

End Sub

有什么想法和帮助吗?

【问题讨论】:

  • 这里还有一个额外的提示。 ws 不需要变量。您已经很好地使用了免费的sheet1 变量——只要在任何地方使用它。如果将来有机会使用不同的工作表(而不是工作表 1),则只需在此处使用 ws
  • 这篇文章看起来和stackoverflow.com/questions/47480022/…相似

标签: vba excel transpose


【解决方案1】:

只要改变这个:

Sheet1.Cells(row, j).Value = Sheet1.Cells(i + j - 1, col).Value

到这里:

Sheet1.Cells(row, j + 1).Value = Sheet1.Cells((row - 1) * stepVal + j, col).Value

同时使用Option Explicit 并声明ij 变量!


不过,我会做的稍有不同。最好在内存中构建数组,然后在完成后将其转储到工作表中。像这样的:

Option Explicit

Public Sub Test()
    Dim v As Variant, output As Variant
    Dim col As Long, i As Long, j As Long

    col = 3

    v = Sheet1.Range("A1:A9").Value 'input range
    ReDim output(1 To Int(UBound(v, 1) / col), 1 To col)

    For i = 1 To UBound(output)
        For j = 1 To col
            output(i, j) = v((i - 1) * col + j, 1)
        Next j
    Next i

    With Sheet1.Range("C1") 'output range
        .Resize(UBound(output, 1), UBound(output, 2)).Value = output
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 2012-12-14
    相关资源
    最近更新 更多