如何使用工作表名称作为整数进行计算?

时间:2015-02-18 11:56:13

标签: excel vba excel-vba

我有很多张(约1000张),其名称为整数,如:1 2 3 5 7 10等。他们是升序但不一致,就像我写的那样。 我有一个vba代码,用于在输入框中创建带有numbername的新工作表,在活动工作表之后(我激活工作表3,运行代码,在输入框中输入4,然后在3之后创建工作表4)。我需要的是解决方法如何(例子):在图纸编号3之后创建一个名为4的新工作表,而不必在工作表3上。

2 个答案:

答案 0 :(得分:1)

以下代码遍历所有工作表。当它到达一个数字较大的那个时,它会在它之前插入新的工作表。

Public Sub Test()
    AddSheetWithNumber shNum:=4
End Sub

Public Sub AddSheetWithNumber(shNum As Long)

    With ThisWorkbook

        Dim sh As Worksheet
        For Each sh In Worksheets
            ' Find first sheet with number greater than new sheet number
            If CLng(sh.Name) > shNum Then
                ' Add worksheet before sheet with larger number
                .Worksheets.Add before:=sh
                ActiveSheet.Name = CStr(shNum)
                Exit For
            End If
        Next

    End With

End Sub

答案 1 :(得分:0)

在我看到你的榜样之前,我提出了类似的解决方案。它也可能有用:

Sub New_Sheet()

Dim ExistingSheet As Integer
Dim NewSheet As Integer
On Error GoTo 30
NewSheet = InputBox("Enter new sheet:", "NEW SHEET")


For i = 3 To Sheets.Count - 3 'this is my work range
ExistingSheet = Sheets(i).Name
If ExistingSheet = NewSheet Then
 MsgBox ("That sheet already exist!")
 Sheets(i).Activate
 GoTo 30
Else
    On Error GoTo 10     'last 4 sheets have textual name like (subtotal, partners, etc) so error came up if I want to add sheet with bigest number(because it's comparing a textual name)
    If NewSheet > ExistingSheet Then   'error came up only in that case for now, so I make it place biggest sheet before textual one.
     GoTo 20
    Else
        ActiveWorkbook.Sheets("Empty Card").Copy _
        after:=Sheets(i - 1)                        'Sheet with formulas and tables prepared for work
        ActiveSheet.Name = NewSheet
        ActiveSheet.Cells(2, 13) = ActiveSheet.Name
    Exit Sub
    End If
End If
20 Next i
10      ActiveWorkbook.Sheets("Empty card").Copy _
        after:=Sheets(i - 1)      'didn't know of "befor" command
        ActiveSheet.Name = NewSheet
        ActiveSheet.Cells(2, 13) = ActiveSheet.Name
30 Exit Sub

End Sub
相关问题