对于复制工作表并使用Application.inputbox重命名的代码,需要取消选项。

问题描述 投票:1回答:3

我有以下代码复制主工作表并使用Application.Inputbox重命名它。

'Generates input box to name the new Sheet and checks duplicate names

Set wks = ActiveSheet
    Do While sName <> wks.Name
        sName = Application.InputBox _
          (Prompt:="Enter New Year")
        On Error Resume Next
        wks.Name = sName
        On Error GoTo 0
    Loop
    Set wks = Nothing

除非用户单击取消,否则此工作正常。目前出来的是;

用户输入内容并单击“确定”=复制主表并重命名为输入值。

用户输入任何内容并单击“确定”=输入框循环,直到输入值并单击“确定”或取消单击。

用户单击“取消”=复制主表并重命名为“False”。

用户点击的取消结果'取消'=子兴奋,没有复制或改变。

有帮助吗?

excel vba excel-vba
3个回答
2
投票

我会以下列方式更改您的代码。

Dim sname As Variant
Dim wks As Worksheet

    Set wks = ActiveSheet
    Do While sname <> wks.Name
        sname = Application.InputBox _
                (Prompt:="Enter New Year")
        If sname = vbFalse Then
            MsgBox "You pressed Cancel"
        Else
            On Error Resume Next
            wks.Name = sname
            On Error GoTo 0
        End If
    Loop
    Set wks = Nothing

如果用户按下取消,则sname将成为值为False的布尔值


0
投票

您可以通过查找vbNullString(空)字符串来检测取消

    Set wks = ActiveSheet
        Do While sName <> wks.Name
            sName = Application.InputBox _
              (Prompt:="Enter New Year")
        If sName = vbNullString Then
                MsgBox ("Cancel button clicked!")
Exit Sub
            End If
            On Error Resume Next
            wks.Name = sName
            On Error GoTo 0
        Loop
        Set wks = Nothing

0
投票

使用上面的帮助将其添加到我的代码中;

'Generates input box to name the new Sheet and checks duplicate names


    Set wks = ActiveSheet
    Do While sname <> wks.Name
        sname = Application.InputBox _
                (Prompt:="Enter New Year")
        If sname = vbFalse Then
            MsgBox "You pressed Cancel"
            Application.DisplayAlerts = False
            Sheets("MASTER (2)").Delete
            Application.DisplayAlerts = True
            Sheets("MASTER").Visible = False

Exit Sub

        Else
            On Error Resume Next
            wks.Name = sname
            On Error GoTo 0
        End If
    Loop
    Set wks = Nothing

上面的帮助允许代码接受有效输入,检测重复输入,检查没有输入并根据需要循环,如果单击“取消”按钮,则它通知用户。在删除不需要的工作表(从代码中较早的主工作表中复制)后,我添加了进一步的代码来退出sub。

感谢大家的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.