尝试在xls工作表上设置名称时出现1004错误

时间:2013-05-16 19:04:44

标签: vba xlsx

我正在尝试创建名称取自sheet1单元格的工作表,但在执行1004 error

时,我总是得到Worksheets(Worksheets.Count).name = companyName

我尝试按PrefferedName设置工作表名称并且工作...我还检查了MsgBox companyName变量的最后一个工作表名称...

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

除了工作表名称不唯一外,如果工作表名称长度超过31个字符,您还可能会收到错误1004。 尝试做:
var tasks = allRequests.Select(async request => { ... }); await Task.WhenAll(tasks);