在Excel中使用for循环创建创建工作表时出错

时间:2019-02-08 12:22:02

标签: excel vba

作为更大的Macro的一部分,我必须在特定位置创建一定数量的工作表。

要做到这一点,并且由于我是宏(以及一般编程)的入门者,因此我在一个简单的场景下进行了测试。

我看到了类似的问题here

但是,将代码修改为适合我的情况,我只能创建第一张纸,然后在下面出现错误。

现在的代码是这样:

Sub AddSheets()

Dim siteCount As Integer
Dim i As Integer

siteCount = 2


For i = 1 To siteCount
    Name = Cells(i, 26)
    Set site_i = Sheets.Add(after:=Sheets("DLC_" & CStr(Name)))
    site_i.Name = "DLC" & CStr(Name)

Next i
End Sub

我没看到什么?

1 个答案:

答案 0 :(得分:0)

如果您的想法是基于单元格Z1和Z2的值将工作表添加到工作簿中,这是一种可能的解决方案。首先,请确保在工作簿的第一个工作表中的Z1和Z2中确实有一些值。

enter image description here

使用

Z1和Z2,因为在这里原始问题中引用了它们:     Name = Cells(i, 26)Cells()首先获取行,然后获取列。然后运行以下代码:

Option Explicit

Sub AddSheets()

    Dim siteCount As Long
    Dim i As Long
    Dim name  As String
    siteCount = 2

    Dim newWks As Worksheet

    For i = 1 To siteCount
        With Worksheets(1)
            name = .Cells(i, 26)
            If .Cells(i, 26) <> "" Then
                Set newWks = Worksheets.Add(after:=Worksheets(Worksheets.Count))
                newWks.Name = .Cells(i, 26)
            Else
                MsgBox Cells(i, 26).Address & "is empty"
            End If
        End With
    Next i

End Sub

工作表添加有: Set newWks = Worksheets.Add(after:=Worksheets(Worksheets.Count))

其名称更改为 newWks.Name = .Cells(i, 26)

How to Add a Named Sheet at the end of all excel sheets

如果两次运行代码,则会出现错误,因为具有相应名称的工作表已经存在于工作簿中。

相关问题