-2

I have written a vba code that has a "for next" loop 1 to 10 and displays the result in respective rows in ColumnA, i want when it reaches row 5 the macro should automatically create a new sheet named "New sheet" and the "for next" continues from 6 til it reaches 10. I'm new to VBA and the code I wrote doesn't seem to work.

My VBA code:

Sub test()

Dim a As Long
Dim WS As Worksheet

Set WS = Worksheets.Add(After:=Worksheets(1))
WS.Name = "New Sheet"

n = 1
col1 = 1

For a = 1 To 10

    If n <= 5 Then

        Cells(n, col1).Value = a
        n = n + 1

    End If

    If n > 5 Then

        WS.Cells(n, 1).Value = a
        n = n + 1

    End If

Next a


  End Sub
khakiout
  • 2,372
  • 25
  • 32
YungKing
  • 33
  • 9

1 Answers1

0

Your code can be further improved if you follow what's posted here.
As for your question, you can try below:

Sub Test()
    Dim newWS As Worksheet
    Dim a As Long
    Dim n As Long: n = 1

    With Thisworkbook.Sheets("SheetName")
        For a = 1 To 10
            If n > 5 Then
                On Error Resume Next
                Set newWS = Thisworkbook.Sheets("New Sheet")
                On Error Goto 0
                If newWS Is Nothing Then
                    Set newWS = Thisworkbook.Sheets.Add(After:= _
                        Thisworkbook.Sheets(Thisworkbook.Sheets.Count))
                    newWS.Name = "New Sheet"
                End If
                newWS.Cells(n, 1).Value = a
            Else
                .Cells(n, 1).Value = a
            End If
            n = n + 1
        Next
    End With
End Sub
Community
  • 1
  • 1
L42
  • 19,427
  • 11
  • 44
  • 68