我有复制工作表的代码,需要帮助来添加工作表名称必须在范围内的条件

时间:2018-08-24 05:41:12

标签: excel vba excel-vba

我在此网站上找到了一些不错的代码,它们很好用,但我对vba还是陌生的,不确定,需要添加条件以使创建的工作表名称出现在命名范围“ WeekEnd”中

Sub Test()
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Sheets("MASTER")
    Dim newws As Worksheet, sh As Worksheet, newname
    Dim query As Long, xst As Boolean, info As String

retry:
    xst = False
    newname = Application.InputBox("Enter new week ending date in YYMMDD format:", info, , , , , , 2)
    If newname = "False" Then Exit Sub

    For Each sh In wb.Sheets
        If sh.Name = newname Then
            xst = True: Exit For
        End If
    Next

    If Len(newname) = 0 Or xst = True Then
        info = "Sheet name is invalid. Please retry."
        GoTo retry
    End If

    ws.Copy after:=ws: Set newws = ActiveSheet: newws.Name = newname
End Sub

1 个答案:

答案 0 :(得分:0)

If Len(newname) = 0 Or xst = True Or _
  IsError(Application.Match(newname, Range("WeekEnd"), 0)) Then

如果命名范围内的工作表名称不匹配,则Match()返回错误,并使用IsError()进行检查