程序 Excel 循环将一列值复制到 3 个单独的列中



我有一个很长的数据表,有数千列和几行,我需要几天时间才能编辑,但我觉得必须有一种方法来编程我想做的事情。不过我是一个编程菜鸟,如果这很简单(或不可能(,很抱歉。

现在我有 3 列"V"A"和"D"。我有一个带有 V A 和 D 值的参与者列表。问题是,参与者值在一列中,也就是说,对于每个参与者,我每列中有 90 个值。我需要将这 90 个值分成 30 个"V"、30 个"A"和 30 个"D"值,并复制到各自的列中,然后切换到下一个参与者列并执行相同的操作。

基本上,我有:

V    A    D       Participant 1  Participant 2  Participant 3  Etc.
                    1              1              1              1
                    2              2              2              2
                    3              4              3              5
                    4              6              9              0 
                    ...            ...            ...            ...
                    90             90             90             90

我需要打破参与者 1 的 90 个值(将前 30 个值放在 V 列中,接下来的 30 个值放在 A 列中,接下来的 30 个值放在 D 列中(,然后让 Excel 切换到参与者 2 将其 90 个值分解为 V A 和 D 列。然后重复此过程。

提前感谢您提供的任何建议。

此代码有两个for循环,一个用于每个参与者(列(,一个用于每个包含 30 个值的块。它从第一个参与者复制前 30 个值,并将其粘贴到另一个工作表上。然后对下一个 30 块和第三个 30 块重复此操作。然后,外部循环移动到下一个参与者。

在此示例中,我在工作表"Sheet2"的第 B 列、C 列和D列中有三个参与者,数据值从第 2 行开始。输出被粘贴到"Sheet3",从第 F 列开始

Sub transpose()
    Dim i As Integer
    Dim j As Integer
    Dim outCol As Integer
    Dim outRow As Integer
    Dim intStart As Integer
    Dim intEnd As Integer
    Dim wksData As Worksheet
    Dim wksOut As Worksheet
    Dim strParticipant As String
    Dim strRange As String
    Set wksData = Worksheets("Sheet2")
    Set wksOut = Worksheets("Sheet3")
    outRow = 2             'starting in row 2
    For i = 2 To 5          'columns of participants'
        strParticipant = wksData.Cells(1, i).Value
        outCol = 6              'output begins in column 6 ("F")
        For j = 1 To 3      'blocks of values per participant
            intStart = (j - 1) * 30 + 2 'increment for every block of 30 (starting at row 2)
            intEnd = intStart + 29
            wksData.Range(Cells(intStart, i), Cells(intEnd, i)).Copy
            wksOut.Cells(outRow, outCol).PasteSpecial Paste:=xlValues
            outCol = outCol + 1
        Next j
        'The two lines below will output the participant's name - uncomment if required.
'            strRange = "E" & outRow & ":E" & outRow + 29
'            wksOut.Range(strRange) = strParticipant
        outRow = outRow + 30    'change the output row
    Next i
    Set wksData = Nothing
    Set wksOut = Nothing
End Sub

相关内容

最新更新