我编写了一个vba代码,其中"for next"
循环为1到10,并在ColumnA中的相应行中显示结果,我希望当它到达第5行时,宏应该自动创建一个名为“New sheet”的新工作表“并且"for next"
从6开始直到达到10.我是VBA的新手,我编写的代码似乎不起作用。
我的VBA代码:
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
答案 0 :(得分:0)
如果您按照what's posted here进行操作,可以进一步改进您的代码 至于你的问题,你可以尝试下面的内容:
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