1

我正在尝试创建名称取自单元格的工作表,但在执行时 sheet1我总是得到一个1004 errorWorksheets(Worksheets.Count).name = companyName

我尝试设置工作表名称PrefferedName并工作......我还检查了MsgBoxcompanyName变量是否具有最后一张工作表的名称......

Sub Find2()
    Dim i, k As Integer
    Dim j, l As Integer
    Dim Counter As Integer
    Dim dateAnnounced As Date
    Dim fromDate As Date
    Dim currentCellDate As Date
    Dim daysBefore As Integer
    Dim kk As Integer
    Dim from1 As Integer
    Dim companyName As Variant

    Set originsheet = ThisWorkbook.Worksheets("Sheet1")

    daysBefore = 30

    i = 3
    j = 4
    Counter = 0
    k = 5
    l = 4179
    dateAnnounced = Cells(i, j).Value

    For Each cel In Range(Cells(1, k), Cells(1, 4179))
        currentCellDate = cel.Value

        If currentCellDate = dateAnnounced Then
             MsgBox k
            Exit For
        End If

        k = k + 1
    Next cel

    kk = k
    from1 = k - daysBefore

    ThisWorkbook.Sheets.Add after:=Sheets(Worksheets.Count)
    companyName = Worksheets("Sheet1").Cells(i, j - 1).Value
    Worksheets(Worksheets.Count).name = companyName

    MsgBox name

    For Each cel In Range(Cells(1, from1), Cells(1, kk))
        If from1 = kk Then
             MsgBox cel.Value
            Exit For
        Else
            Counter = Counter + 1
        End If

        from1 = from1 - 1
    Next cel

    MsgBox Counter

End Sub
4

2 回答 2

0

如果您多次运行此代码,您将收到 1004 运行时错误,因为它会尝试添加具有相同名称的工作表。所有工作表都必须具有唯一的名称。在创建新工作表之前,您可能需要添加检查以确保具有该名称的工作表不存在。就像是:

companyName = Worksheets("Sheet1").Cells(i, j - 1).Value
WorksheetExists = False
For Each Sht In ThisWorkbook.Worksheets
    If UCase(Sht.Name) = UCase(companyName) Then
        WorksheetExists = True
        Exit For
    End If
Next Sht
If WorksheetExists Then Exit Sub

ThisWorkbook.Sheets.Add after:=Sheets(Worksheets.Count)
Worksheets(Worksheets.Count).Name = companyName
于 2015-10-19T16:06:43.867 回答
0

除了不唯一的工作表名称之外,如果工作表名称的长度超过 31 个字符,您还会收到错误 1004。
尝试做:
Worksheets(Worksheets.Count).name = Left(companyName, 31)

于 2017-07-12T13:52:10.013 回答