这是我的代码:
Private Sub New_User_Create_Click()
CreateUsername_L = LCase(Create_User_Text.Text)
For Each ws In Worksheets
If (Worksheets(CreateUsername_L).Name <> "") Then
MsgBox "Username is already taken! Try again!"
Create_User_Text.Text = ""
NewUser.Hide
Exit For
Else
Dim work As Worksheet
With ThisWorkbook
Set worksheetname = .Sheets.Add(After:=Worksheets(Worksheets.Count))
worksheetname.Name = CreateUsername_L
On Error Resume Next
Create_User_Text.Text = ""
NewUser.Hide
[B1].Value = (UserName + "'s Personal Profile")
Exit For
End With
End If
Next ws
End Sub
如果你可以帮助我,我将不胜感激 (也只有在不满足条件时才会出现错误,例如,没有与&#34; CreateUsername_L&#34;同名的工作表。满足条件时,带有&#34;用户名的消息框已被占用.. 。&#34;只有在发生此错误时不满足条件时才显示出来)
答案 0 :(得分:2)
您无法像您尝试那样测试工作表名称的存在。 &#39;下标超出范围&#39;错误正在查找该工作表名称,如果找不到,那么您将收到错误消息。您可以编写一个函数来测试名称的存在并使用它。这是我的:
Public Function doesSheetNameExist(inputName As String) As Boolean
Dim ws As Worksheet
On Error GoTo ErrorCatch
Set ws = Thisworkbook.Worksheets(inputName)
'if no error here then worksheet exists
doesSheetNameExist= True
CloseFunction:
Exit Function
ErrorCatch:
doesSheetNameExist= False
Resume CloseFunction
End Function
这处理函数内的错误。或者,您可以遍历每个工作表并测试名称。
然后你替换你的行
If (Worksheets(CreateUsername_L).Name <> "") Then
带
If doesSheetNameExist(CreateUsername_L) Then