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 に答える