为什么我的第二次调用时删除程序不起作用?

时间:2015-08-04 19:36:42

标签: excel vba

我编写了以下代码来插入新工作表,重命名并删除它们。 但是当我第二次调用删除子时,它不会起作用,因为NumSheets会变为零,即使有超过2张。

Public NumSheets As Integer
Sub NewCCSheet()
    Dim n As Integer

    n = InputBox("How many 16-24 Vehicle C.C.sheets do you need? (Enter a number only)")

    NewVehicle (n)
End Sub
Function NewVehicle(n As Integer)
    For i = 1 To n
        NumSheets = NumSheets + 1
        Worksheets("16-24 Vehicle C.C.1").Copy Before:=Worksheets("Ave. Vehicle C.C.")
        ActiveSheet.Name = "16-24 Vehicle C.C." & CStr(NumSheets + 1)
        Range("B5").ClearContents
        Range("D4").ClearContents
        Range("E12:E13").ClearContents
        Range("B15:E23").ClearContents
        MsgBox NumSheets
    Next i
End Function
Sub DeleteSheets()
    MsgBox NumSheets
    Dim Ans As String
    If NumSheets = 0 Then
        MsgBox "You can't delete 16-24 Vehicle C.C.1 Worksheet"
        Exit Sub
    End If
    Ans = MsgBox("Delete current worksheet?", vbYesNo)
    If Ans = vbYes Then
        NumSheets = NumSheets - 1
        On Error Resume Next
        Application.DisplayAlerts = False
        ActiveSheet.Delete
        Application.DisplayAlerts = True
        MsgBox NumSheets
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

在某些情况下,您的代码可能会从NumSheets中删除1而不删除工作表 - 例如,如果只剩下1个,我不相信它会从工作簿中删除最后一个工作表。 On Error Resume Next可能会导致其他错误导致NumSheets与实际页数不匹配。

您是否可以使用Sheets().Count代替NumSheets?如果是这样的话,那就会给你一个给定时间内实际张数的最新,准确的数量,你不必自己跟踪它们的数量。所以你的代码看起来像:

Sub NewCCSheet()
    Dim n As Integer

    n = InputBox("How many 16-24 Vehicle C.C.sheets do you need? (Enter a number only)")

    NewVehicle (n)
End Sub

Function NewVehicle(n As Integer)
    For i = 1 To n
        Worksheets("16-24 Vehicle C.C.1").Copy Before:=Worksheets("Ave. Vehicle C.C.")
        ActiveSheet.Name = "16-24 Vehicle C.C." & CStr(Sheets().Count + 1)
        Range("B5").ClearContents
        Range("D4").ClearContents
        Range("E12:E13").ClearContents
        Range("B15:E23").ClearContents
    Next i
End Function

Sub DeleteSheets()
    Dim Ans As String
    If Sheets().Count = 0 Then
        MsgBox "You can't delete 16-24 Vehicle C.C.1 Worksheet"
        Exit Sub
    End If
    Ans = MsgBox("Delete current worksheet?", vbYesNo)
    If Ans = vbYes Then
        On Error Resume Next
        Application.DisplayAlerts = False
        ActiveSheet.Delete
        Application.DisplayAlerts = True
    End If
End Sub