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