0

我在excel表中有如下数据

A,B,C
D,E,F

我想将其转换为

A,B
A,C
B,C
D,E
D,F
E,F

我有以下宏,只能这样:

A,B
A,C
D,E
D,F

如何调整以下代码以达到目的?

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
4

1 回答 1

0

我在您的宏中添加了第二个循环以实现我所理解的结果:

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

Dim col1 As Variant
Dim cell As Range
Dim colCounter As Long
Dim colCounter2 As Long

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

    For colCounter = 1 To Selection.Columns.Count - 1

        'col1 = sourceRow.Cells(colCounter).Value
        'For Each cell In sourceRow.Cells
        col1 = sourceRow.Cells(colCounter).Value
        For colCounter2 = colCounter + 1 To Selection.Columns.Count
            Set cell = sourceRow.Cells(, colCounter2)

            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 colCounter2

    Next colCounter

Next sourceRow

请注意,如果您将选择复制到一个局部变量(数组)中进行处理,在数组中创建结果,然后在完成后将内容复制回工作表,则性能会大大提高。除非您正在处理更大的数据集,否则这可能并不重要。

于 2013-01-19T03:31:42.760 回答