excel - VBA循环要求用户输入新的工作表名称

标签 excel vba loops input

我目前正在创建一个新工作表,并使用唯一的工作表名称为其用户命名。我有一个循环检查一次,如果第一次出错,则提示用户输入新的工作表名称,但我不知道一旦发生这种情况如何重新启动循环。

Dim myValue As Variant
    myValue = InputBox("Enter New Sheet Name")
    
    Dim exists As Boolean
    exists = True
While exists = True
    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = myValue Then
            exists = True
            myValue = InputBox("You entered an existing sheet name. Please enter a unique sheet name")
        Else
        exists = False
        End If
        Next i
    i = 1
Wend

Sheets("NewSheet").Name = myValue

End Sub
谢谢!

最佳答案

使用工作表重命名错误处理方法,您可以获得最快、最短的方法来确定名称的唯一性和可接受性,因为有字符组成和名称长度restrictions .
试试这个代码:

Sub test1()
    Dim newWS As Worksheet, myValue As String, prompt As String
    prompt = "Enter New Sheet Name"     'start prompt
    
    Set newWS = ThisWorkbook.Worksheets.Add
    
    Do
        myValue = InputBox(prompt)
        On Error Resume Next            'disable the system response to errors
        newWS.Name = myValue            'trying to rename
        If Err.Number = 0 Then Exit Do  'check the Err object; if no error then exit loop
        On Error GoTo 0                 'enable the system response to errors
        prompt = "You entered an existing or unacceptable sheet name." & _
                 vbLf & "Please enter a unique sheet name"  'next try prompt
    Loop
End Sub

关于excel - VBA循环要求用户输入新的工作表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68686378/

相关文章:

jquery - HandsonTable setDataAtCell 不起作用

VBA - With and selection 命令太慢了。我怎样才能更好地优化它以更快地运行?

python - 使用 sqlite 的 fetchone() 读取循环中的第一行

java - 使用 for 循环将奇数存储在数组中

python - Plotly 循环中的一些子图

python - openpyxl 字体条件格式

java - 在 JExcel 中写入后,如何在 Excel 中显示 'activate' 超链接?

java - 如何释放 XSSFWorkbook 占用的内存?

excel - 选择具有空白行的范围单元格

vba - 使用 vba 将列复制并粘贴到 Excel 中的行中