检查表单名称以避免重复

我正在研究一个macros,其中的一部分从用户那里获得input,询问他/她想要重命名表。 它工作正常,但如果由用户提供的名称已被其他工作表使用,则会遇到运行时错误。 我明白为什么会出现错误,但不知道如何提醒用户并处理错误。

我的代码如下:

'Change sheet name Dim sheetname As String sheetname = InputBox(Prompt:="Enter Model Code (eg 2SV)", _ Title:="Model Code", Default:="Model Code here") wsCopyTo.Name = sheetname 

有两种方法来处理这个问题。

首先,捕捉错误,检查是否有错误,并提出build议,然后将错误陷回到原来的状态

 Dim sheetname As String sheetname = InputBox(Prompt:="Enter Model Code (eg 2SV)", _ Title:="Model Code", Default:="Model Code here") On Error Resume next Err.Clear 'ensure previously unhandled errors do not give a false positive on err.number wsCopyTo.Name = sheetname If Err.Number = ?? then 'go back and ask for another name On Error Goto 0 

其次,检查所有当前表单名称,看看是否有匹配

 Dim sheetname As String Dim sh 'as Sheet sheetname = InputBox(Prompt:="Enter Model Code (eg 2SV)", _ Title:="Model Code", Default:="Model Code here") for each sh in ActiveWorkbook.Sheets If lower(sh.name)=lower(sheetname) then 'Goback and ask for another name Next wsCopyTo.Name = sheetname 

我刚刚写了一篇关于使用Excel的本地重命名表对话框来做到这一点。 这样你就可以检查重复,非法字符和名字太长的错误。 这是一个添加表单并调用对话框的例程。 如果用户不重命名,那么新的工作表被删除:

 Sub PromptForNewSheetWithName() Dim DefaultSheetName As String ActiveWorkbook.Worksheets.Add DefaultSheetName = ActiveSheet.Name Application.Dialogs(xlDialogWorkbookName).Show If ActiveSheet.Name = DefaultSheetName Then MsgBox "You didn't name the new sheet." & vbCrLf & _ "Processing cancelled", vbExclamation Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True End If End Sub 

整个post在:http: //yoursumbuddy.com/prompt-to-name-new-sheet/

首先循环你所拥有的名字,然后把他们的名字和用户给出的名字进行比较。 如果匹配,写一条消息说已经使用了。 之后退出。

 For i = 1 To ActiveWorkbook.Worksheets.Count If Worksheets(i).Name = sheetname then msgbox "This name is already in use!" exit sub End if Next 

最简单的方法是创build一个Worksheetvariables并将其设置为用户input的内容(您也可以修剪()以除去前导和尾随空格)。

如果没有,那么名字是安全的使用。 如果不是什么,那么它已经存在。

 Dim oWS As Worksheet On Error Resume Next Set oWS = ThisWorkbook.Worksheets(sheetname) If oWS Is Nothing Then ' Safe to use the name Debug.Print """" & sheetname & """ is save to use." Err.Clear wsCopyTo.Name = sheetname If Err.Number <> 0 Then MsgBox "Cannot use """ & sheetname & """ as worksheet name." Err.Clear End If Else Debug.Print """" & sheetname & """ exists already! Cannot use." ' worksheet with same name already! ' handle it here End If Set oWS = Nothing On Error GoTo 0 

您也可以将其放入循环,直到find未使用的图纸名称。