vba - 如何将多列转换为单列?

标签 vba excel

我有一个看起来像这样的表:

Col1        Col2        Col3        Col4
a       b       c       d
e       f       g       h

我需要将其转换为:
Col1        New
a       b
a       c
a       d
e       f
e       g
e       h

我有大量数据,手动操作是不可能的。有谁知道一个快速的方法来做到这一点?我希望有一种内置方式(例如粘贴->转置或函数?)。如果没有的话,有人可以指出一个相关的 VBA 示例,因为我对 VBA 有点生疏。

最佳答案

选择要转换的数据(不包括列标题)并运行以下宏。

Sub Transform()

    Dim targetRowNumber As Long
    targetRowNumber = Selection.Rows(Selection.Rows.Count).Row + 2

    Dim col1 As Variant
    Dim cell As Range

    Dim sourceRow As Range: For Each sourceRow In Selection.Rows

        col1 = sourceRow.Cells(1).Value
        For Each cell In sourceRow.Cells

            If Not cell.Column = Selection.Column Then
                Selection.Worksheet.Cells(targetRowNumber, 1) = col1
                Selection.Worksheet.Cells(targetRowNumber, 2) = cell.Value
                targetRowNumber = targetRowNumber + 1
            End If

        Next cell

    Next sourceRow

End Sub

关于vba - 如何将多列转换为单列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1780235/

相关文章:

python - 只读取 Excel 文件的标题

Excel 宏预期函数或变量

vba - 数字格式有问题

arrays - 按数字键对字典排序

excel - 如果单元格在vba中有小数点,有没有办法引用?

excel - 使用初始名称创建单词

vba - 当工作表有过滤器时,为什么 ActiveSheet.FilterMode 返回 False?

vba - 从单元格动态引用工作表 - VBA

sql-server - 从 Excel 连接到 SQL Server 用户定义函数

vba - 将行更改的公式向下拖动除一个间隔之外的另一个间隔