VBA-For循环仅打印最后一个项目

时间:2018-12-07 16:03:42

标签: excel vba

我正在弄乱一个工作簿,并试图将一行中的行自动填充到一列中。

我要复制的行数是我可以在新工作表中打印的列数的两倍,因此,只要行号达到最大列数,它就会创建一个新工作表并打印到其中。

它适用于新工作表中的第一个数字,但是一旦到达ElseIf y > 11行,则仅打印数组中的最后一个数字。

Sub ColumnToRow()

    Dim x As Integer
    Dim y As Integer
    Dim z As Integer
    Dim sht As Worksheet
    Dim myarray() as Variant

    Application.ScreenUpdating = False

    ReDim myarray(11 To 30)
    For x = 11 To 30
        myarray(x) = ActiveSheet.Cells(x, 1).Value
        y = x - 10
    Next x

    For y = 1 To 20
        If y = 11 Then
            z = 1

            Worksheets("0049-0050").Copy After:=Worksheets("0049-0050")
            Set sht = ActiveSheet
            sht.Range(Cells(50, z), Cells(40, y - 1)).ClearContents
            sht.Cells(50, z).Value = myarray(y + 10)

            z  = z + 1 'Typist's note:  so, "z = 2"?
        ElseIf y > 11 Then
            For z = 2 To 10
                sht.Cells(50, z).Value = myarray(y + 10)
            Next z
        Else
            Sheets("0049-0050").Cells(50, y).Value = myarray(y + 10)
        End If
    Next y

    Application.ScreenUpdating = True

End Sub

code

1 个答案:

答案 0 :(得分:0)

@BruceWayne我弄清楚了我的问题所在,我试图在ElseIf语句中运行一个for循环,这导致它完成了嵌套循环而不运行外部循环,所以我只是使用整数进行了循环增量代替:

Sub ColumnToRow()

Dim X As Integer
Dim y As Integer
Dim z As Integer
Dim sht As Worksheet
Dim myarray() As Variant


Application.ScreenUpdating = False

    ReDim myarray(11 To 30)
    For X = 11 To 30
        myarray(X) = ActiveSheet.Cells(X, 1).Value
        y = X - 10
    Next X


    For y = 1 To 20
        If y = 11 Then
         z = 1
            Worksheets("0049-0050").Copy After:=Worksheets("0049-0050")
            Set sht = ActiveSheet
            sht.Range(sht.Cells(50, z), sht.Cells(50, y - 1)).ClearContents
            sht.Cells(50, z).Value = myarray(y + 10)

        ElseIf y > 11 Then

            sht.Cells(50, z).Value = myarray(y + 10)

        Else
            Sheets("0049-0050").Cells(50, y).Value = myarray(y + 10)
        End If
            z = z + 1
    Next y

Application.ScreenUpdating = True

结束子

  • 谢谢