简体   繁体   English

向 excel 工作簿添加新工作表

[英]Add a new sheet to excel workbook

I am trying to add a new sheet to my workbook and I was able to find some suggestions online.我正在尝试在我的工作簿中添加一个新工作表,并且我能够在网上找到一些建议。 I ended up using this piece of code but for some reason, it is not working.我最终使用了这段代码,但由于某种原因,它不起作用。 I don't know why because to me the logic makes sense and there seems to be no problem with the syntax.我不知道为什么,因为对我来说逻辑是有道理的,而且语法似乎没有问题。 I am guessing it's something I can't see and since I am new to VBA I could really use someone's input.我猜这是我看不到的东西,因为我是 VBA 的新手,我真的可以使用某人的输入。

Private Sub PopulateTaskList()

'Adds new sheet called task list
    Dim exists As Boolean
    Dim i As Integer
   
    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = "Task List" Then
        exists = True
        Else
            If exists = False Then
                Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Task List"
            End If
        End If
    Next i

End Sub

Use Exit Sub instead when it's detected.检测到时请改用Exit Sub

That way, if it makes it out of the loop (but not out of the sub), you know it hasn't been created yet.这样,如果它脱离了循环(但没有脱离子),你就知道它还没有被创建。

Private Sub PopulateTaskList()
    'Adds new sheet called task list
    Dim i As Integer
   
    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = "Task List" Then Exit Sub
    Next
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Task List"

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM