VBA Multiple Passwords excel - vba

Afternoon, first off, VBA noob here so take it easy on me and please spell out answers or provide full code as I am not familiar enough to just insert chunks as needed. I need a little more context.
What I am trying to do, is have multiple correct passwords but each password will do something different. This is as far as I have gotten and its current operation is as follows:
Sub zebra()
Dim MyPassword As String
MyPassword = "Zebra" ' Change this to alter password
If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then
Dim Ans As Boolean
Const Pword As String = "Zebra" ' This should match password
Ans = False
Do While Ans = False
If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
Ans = True
End If
Loop
Exit Sub
End If
Sheets("Level 3").Visible = True ' This selects what sheet should become visible
End Sub
Essentially, pop-up window, enter Zebra password, loop if wrong, unlock sheet "level 3 if correct". What I would like is if it could have the password Zebra unlock Level 3 but another password such as "Tiger" would unlock another sheet such as "Level 2".
In the end, what ever the password is, I need a specific and basically unique answer but am unsure how to code multiple passwords.
PLEASE NOTE: I would like to avoid writing multiple codes because the user interface needs to be simple enough for any level of proficiency to click a button, enter a password, and receive the correct information with ALL other information being hidden as it is highly confidential.

First off all, the way you are trying to apply "security" is not the appropriate, so I suggest to find another alternatives to secure your file.
An alternative to what you are trying to do is to use Case Statement.
An example:
Select Case MyPassword
Case "Zebra"
Sheets("Level 3").Visible = True
Case "Tiger"
Sheets("Level 3").Visible = False
Sheets("Level 2").Visible = True
Case "Elephant"
AnotherAction
Case ""
Msgbox "Password can not be empty."
Case Else
Msgbox "Wrong password."
End Select
Hope it helps.

Here is another example
Option Base 1
Sub CheckPassword()
Dim allPasswords(3)
allPasswords(1) = "Zebra"
allPasswords(2) = "Tiger"
allPasswords(3) = "Monkey"
Dim passwordEntered As String
Dim iChanceCount As Integer
Dim ws As Worksheet
Do While True
passwordEntered = InputBox("Please enter password to continue.", "Enter Password")
If passwordEntered = allPasswords(1) Then
Set ws = Sheets("Level 1")
Else
If passwordEntered = allPasswords(2) Then
Set ws = Sheets("Level 2")
Else
If passwordEntered = allPasswords(3) Then
Set ws = Sheets("Level 3")
End If
End If
End If
'see if we set the worksheet
If ws Is Nothing Then
iChanceCount = iChanceCount + 1
'give them 5 tries then exit
If iChanceCount >= 5 Then Exit Sub
Else
'we have a worksheet so make it visible and exit
ws.Visible = xlSheetVisible
Exit Sub
End If
Loop
End Sub

This should work, however, you should definitely not use this for sensitive data. If you want to restrict access to diferent sheets for each user, I recommend simply having a separate workbook for each user and having yourself a master file that collects data from all of these workbooks.
Sub testy2ElectricBoogaloo()
dim i as long, ans as boolean
Dim mystr As String
ans = False
ReDim arr(1 To Worksheets.Count, 1 To 2)
For i = 1 To UBound(arr)
arr(i, 1) = Worksheets(i).Name
'My code makes every password simply the sheet name followed by a smiley face.
'Adjust to fit your actual passwords.
arr(i, 2) = Worksheets(i).Name & " :)"
Next i
Do While ans = False
mystr = InputBox("Please enter password to continue.", "Enter Password")
If mystr = vbNullString Then Exit Sub
For i = 1 To ThisWorkbook.Worksheets.Count
If mystr = arr(i, 2) Then ans = True: Worksheets(arr(i, 1)).Visible = True: Exit For
Next i
Loop
End Sub

Related

RunTime Error 13, Type Mismatch MsgBox Cancel

Getting a Run-Time Error 13 type mistmatch error when clicking cancel on a message box.
I tried making the following script to handle if a message box is empty, however upon bug checking, clicking cancel on the message box throws it all out.
Any ideas?
Private Sub ChangeDebtAmounts_Click()
Dim Debt1 As Integer, Debt2 As Integer, Debt3 As Integer, Debt4 As Integer
Dim D1Range As String, D2Range As String, D3Range As String, D4Range As String
D1Range = ActiveSheet.Range("Y15")
D2Range = ActiveSheet.Range("Y16")
D3Range = ActiveSheet.Range("Y17")
D4Range = ActiveSheet.Range("Y18")
Debt1 = InputBox("Please Enter in the account limit for " & D1Range)
If Debt1 = "" Then
MsgBox ("Setting " & D1Range & " to Zero, No Value Entered")
Else
Range("AA15").Value = Debt1 - Range("S58")
End If
End
End Sub
The type mismatch is with the InputBox rather than the MsgBox. To fix it, it is enough to change Dim Debt1 As Integer to Dim Debt1 As Variant. Also, you are using MsgBox as a sub rather than a function so the correct syntax should be
MsgBox "Setting " & D1Range & " to Zero, No Value Entered"
rather than
MsgBox ("Setting " & D1Range & " to Zero, No Value Entered")
In this case the parentheses are harmless, but if you try to give additional arguments to MsgBox while using it as a sub then you will get a syntax error.
Here's a slightly different take on your question. See my comments within the code.
(It's longer just because of the comments; optionally, you can remove any lines of comments, as well as any other blank lines.)
Private Sub ChangeDebtAmounts_Click()
Dim Debt1, Debt2, Debt3, Debt4 'data type "Variant" is assumed
Dim D1Range As String,D2Range As String,D3Range As String,D4Range As String
'by using a "With" statement, you can use "." instead of "ActiveSheet."
With ActiveSheet
D1Range = .Range("Y15")
D2Range = .Range("Y16")
D3Range = .Range("Y17")
D4Range = .Range("Y18")
'I added a title to the dialog and a default value of zero
Debt1=InputBox("Enter the account limit for " & D1Range, "Limit?" ,0)
'Check user response:
If Debt1 = "" Or Debt1 = 0 Then
'User clicked cancel or entered zero.
MsgBox "Setting " & D1Range & " to Zero, No Value Entered"
'I assume your next step is to set the input value to zero:
Debt1 = 0
Else
'you don't need to specify ".Value" in most cases (it's assumed)
'also:by using the "." we're referring to ActiveSheet again.
.Range("AA15") = Debt1 - .Range("S58")
End If
End With '(the end of "With ActiveSheet")
End Sub
A couple other thoughts:
it appears like you're going to use different variables for each InputBox but this is not necessary: you can re-use the same variable in this case, without issue.
ActiveSheet just refers to "whichever worksheet (tab) happens to be open when the code is run". It's a good idea to explicitly refer to a specific worksheet, to prevent potential problems in the future.
For example if your cells such as Y15 are on worksheet Sheet1, you could replace ActiveSheet with Sheets("Sheet1").
Alternate method (loop through all 4 cells)
These methods are for demonstration only - if you already have your solution figured out, stick with that, there's no point in wasting time! These are just to show other ways to do the same thing.
Just for fun, here's another alternate method, that loops through all 4 cells Y15:Y18 and repeats the same MsgBox's.
I wasn't sure what happens with the other 3 values the user enters, so I left those blank.
Private Sub demo_Alternate()
Dim userInput As Variant, arr As Variant, myCell
With Sheets("Sheet1") '<<<<<< change this to actual worksheet name
arr = .Range("Y15:Y18") ' arr(1) to arr(4) are now cell references
For Each myCell In arr
userInput = InputBox("Enter account limit for " & myCell, "Limit?", 0)
If userInput = "" Or userInput = 0 Then 'Cancelled or 0 entered
MsgBox "Setting " & myCell & " to Zero, No Value Entered"
userInput = 0
Else
Select Case Split(myCell.Address, "$")(2)
Case 15 'do what you need to for cell Y15
Range("AA15") = userInput - Range("S58")
Case 16
'do what you need to for cell Y16
Case 17
'do what you need to for cell Y16
Case 18
'do what you need to for cell Y16
End Select
End If
Next myCell 'loop to next cell
End With
End Sub
OR, if all four cells are getting from S58 and put into column AA of the same row, like:
...if your end-goal is the pattern:
AA15 = {Y15 or UserEntry} - S58
AA16 = {Y16 or UserEntry} - S58
AA17 = {Y17 or UserEntry} - S58
AA18 = {Y18 or UserEntry} - S58
...then something like this could work (and is even more compact).
Private Sub demo_Alternate2()
Dim userInput As Variant, arr As Variant, myCell, rowNum As Long
With Sheets("Sheet1") '<<<<<<<<<<<<< change this to actual worksheet name
arr = .Range("Y15:Y18") ' arr(1) to arr(4) are now cell references
For Each myCell In arr
userInput = InputBox("Enter account limit for " & myCell, "Limit?", 0)
If userInput = "" Or userInput = 0 Then 'Cancelled or 0 entered
MsgBox "Setting " & myCell & " to Zero, No Value Entered"
Else
rowNum = Split(myCell.Address, "$")(2)
Range("AA" & rowNum) = userInput - Range("S58")
End If
Next myCell
End With
End Sub
One noteworthy technique used here is the use of an array (arr) to read multiple cell values at once instead of a separate line for each cell input.
arr = .Range("Y15:Y18")
...assigns the four cells to the array so you can refer to the array as if:
arr(1) = Y15
arr(2) = Y16
arr(3) = Y17
arr(4) = Y18

Excel VBA & UserForm Login and Password VLOOKUP Table in Sheet

I've been trying to get my login userform to login when clicked based on data in a table in the workbook, but I just can't seem to get the code right.
Details are:
Userform username textbox = UsernameTextbox;
Userform password textbox = PasswordTextbox;
Userform submit button = LoginButton
My workbook has a number of sheets, one of which is "Users". In that sheet, there is a table called "Users_Table". That table has 4 columns:
ID (individual IDs for users) [Column A],
Username [Column B],
Password [Column C],
Admin (answer is "True" or "False" depending on if they have admin rights) [Column D].
I'm trying to do this:
If the username and password is correct for a user AND if the admin column entry is False, then I want to show sheets "Quick Add" and "Overview", I want to make the sheet "Admin" hidden (not VeryHidden since I need to use data on this sheet for other macros), and make "User" sheets VeryHidden so those logged in can't see other users' details. But for users who correctly enter their username and password AND for whom the admin column entry is True, I want to show all sheets.
This is what I have so far:
Private Sub LoginButton_Click()
Dim Username As String
Username = UsernameTextbox.Text
Dim password As String
Password = PasswordTextbox.Text
If IsNull(Me.UsernameTextbox) Or Me.UsernameTextbox = "" Then
MsgBox "You must enter your username.", vbOKOnly, "Required Data"
Me.UsernameTextbox.SetFocus
Exit Sub
End If
If IsNull(Me.PasswordTextbox) Or Me.PasswordTextbox = "" Then
MsgBox "You must enter your Password (case sensitive).", vbOKOnly, "Incomplete Entry"
Me.PasswordTextbox.SetFocus
Exit Sub
End If
Dim temp As String
On Error Resume Next
temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 2, 0)
If Username = temp Then
Err.Clear
temp = ""
temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 3, 0)
On Error Goto 0
If Password = temp Then
Sheets("Quick Add").Visible = xlSheetVisible
Sheets("Overview").Visible = xlSheetVisible
Sheets("Admin").Visible = xlSheetHidden 'This is now just Hidden and not VeryHidden since other macros need to use data on this sheet
Sheets("Users").Visible = xlVeryHidden
MsgBox "Password and Username Accepted. You are now Logged In."
'Unload Me
'Sheets("Quick Add").Select
'Range("A1").Select
Else
Sheets("Quick Add").Visible = xlVeryHidden
Sheets("Overview").Visible = xlVeryHidden
Sheets("Admin").Visible = xlVeryHidden
Sheets("Users").Visible = xlVeryHidden
MsgBox "Username and Password Combination Not Accepted"
End If
Else
Sheets("Quick Add").Visible = xlVeryHidden
Sheets("Overview").Visible = xlVeryHidden
Sheets("Admin").Visible = xlVeryHidden
Sheets("Users").Visible = xlVeryHidden
MsgBox "Invalid Username"
End If
End Sub
This works for the first entry in the "Users_Table", but it won't recognise the Username for the others (and so I don't know if it's recognising the Passwords for users as it's failing on the initial Username check). Any ideas what might be going wrong? I'm also not sure how I'd go about adding in the Admin requirement mentioned above. I need Admins ("True" in "Admin" column, i.e. Column D, in the "Users_Table") to be able to see all sheets; the code above is just for Users and shows "Quick Add" and "Overview" and hides "Admin" and "Users" sheets.
Any help would be much appreciated. Thank you!
Any ideas what might be going wrong?
There are a few errors in the code that don't match your description.
temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, _
Worksheets("Users").Range("Users_Table"), 2, 0)
If Username = temp Then
Here you are matching the UsernameTextbox to column A (ID). The test for existence of the username should be in column B not A. The same mistake is made where you are matching the username onto the ID column A insread of the column B of user names:
temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, _
Worksheets("Users").Range("Users_Table"), 3, 0)
The best approach would be to fetch to row of the user at once (if it exists) and from there get all the attributes.
Private Sub LoginButton_Click()
' Get the user row or exit if not found
Dim r As Range
Set r = Worksheets("Users").Range("Users_Table").Columns(2) _
.Find(UsernameTextbox.text, , xlValues, xlWhole)
If r Is Nothing Then
MsgBox "username not found."
Me.UsernameTextbox.SetFocus
Exit Sub
End If
If Me.PasswordTextbox.Value <> r.Offset(, 1).Value2 Then
MsgBox "Wrong Password."
Me.PasswordTextbox.SetFocus
Exit Sub
End If
' So far user and password are ok
Dim isAdmin As Boolean: isAdmin = r.Offset(, 2).Value2
Sheets("Quick Add").Visible = xlSheetVisible
Sheets("Overview").Visible = xlSheetVisible
Sheets("Admin").Visible = IIf(isAdmin, xlSheetVisible, xlSheetHidden)
Sheets("Users").Visible = IIf(isAdmin, xlSheetVisible, xlSheetVeryHidden)
End Sub
You have made it very complicated. Keep it simple. Try this (untested)
Private Sub LoginButton_Click()
Dim Username As String
Dim password As String
Dim passWs As Worksheet
Dim rng As Range
Dim CorrectDetails As Boolean
Username = UsernameTextbox.Text
password = PasswordTextbox.Text
If Len(Trim(Username)) = 0 Then
UsernameTextbox.SetFocus
MsgBox "Please enter the username", vbOKOnly, "Required Data"
Exit Sub
End If
If Len(Trim(password)) = 0 Then
PasswordTextbox.SetFocus
MsgBox "Please enter the password", vbOKOnly, "Incomplete Entry"
Exit Sub
End If
Set passWs = ThisWorkbook.Worksheets("Users")
With passWs
lrow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lrow
If UCase(Trim(.Range("B" & i).Value)) = UCase(Trim(Username)) Then '<~~ Username Check
If .Range("C" & i).Value = password Then '<~~ Password Check
CorrectDetails = True
'~~> Admin is True
If .Range("D" & i).Value = "True" Then
'
'~~> Do what you want
'
Else
'
'~~> Do what you want
'
End If
Exit For
End If
End If
Next i
'~~> Incorrect Username/Password
If CorrectDetails = False Then
MsgBox "Invalid Username/Password"
End If
End With
End Sub
My Assumptions
In sheet "Users", Col B has username, Col C has password and Col D has Admin values.. If not then please amend the above code as required.
Hello everyone,
I know that is was a long time ago, but maybe it would be useful for sm1 the code above did not work for me, so I modify it for my requirements.
Some details of my code:
CommandButton2 it is my "LogIn Button";
TextBox5 it is my "User / Admin name";
TextBox7 it is my "User / Admin password";
Worksheets("LOG") it is a name and location of the table with "User / Admin names and passwords" data, where col B - usernames, col C - user passwords, col d - admin names, col e - admin passwords. The difference between admin and user rights in my case only in visibility of application (Excel).
Private Sub CommandButton2_Click()
Dim passWs As Worksheet
Dim CorrectDetails As Boolean
Username = TextBox5.Text
password = TextBox7.Text
If Len(Trim(Username)) = 0 Then
TextBox5.SetFocus
MsgBox "Please enter the username", vbOKOnly, "Required Data"
Exit Sub
End If
If Len(Trim(password)) = 0 Then
TextBox7.SetFocus
MsgBox "Please enter the password", vbOKOnly, "Incomplete Entry"
Exit Sub
End If
Set passWs = ThisWorkbook.Worksheets("LOG")
With passWs
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
If UCase(Trim(.Range("B" & i).value)) = UCase(Trim(Username)) Then '<~~ Username Check
If .Range("C" & i).value = password Then '<~~ Password Check
CorrectDetails = True
If CorrectDetails = True Then
Application.Visible = False
Me.TextBox5.Text = ""
Me.TextBox7.Text = ""
LogIn.Hide
UserForm1.Show
End If
Exit For
End If
End If
If UCase(Trim(.Range("D" & i).value)) = UCase(Trim(Username)) Then '<~~ Adminname Check
If .Range("E" & i).value = password Then '<~~ Admin Password Check
CorrectDetails = True
If CorrectDetails = True Then
Application.Visible = True
Me.TextBox5.Text = ""
Me.TextBox7.Text = ""
LogIn.Hide
End If
Exit For
End If
End If
Next i
'~~> Incorrect Username/Password
If CorrectDetails = False Then
MsgBox "Invalid Username/Password"
End If
End With
End Sub

VBA Macro With Password Still Operates When Entered Incorrectly

I have a VBA macro in an Excel sheet that refreshes a SQL query but is password protected--or so I thought. How the macro should work is when you click the button, a password prompt appears and if entered correctly, the query refreshes. If entered incorrectly, nothing should happen.
What I recently discovered is that even if someone enters the password incorrectly, the query refreshes anyways. What would I enter into my code to stop the macro from running if the password is incorrect?
Sub Button1_Click()
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")
Select Case password
Case Is = False
'do nothing
Case Is = "Select15"
Range("A1").Value = "Code"
Case Else
MsgBox "Incorrect Password"
End Select
For Each sh In Worksheets
If sh.FilterMode Then sh.ShowAllData
Next
ActiveWorkbook.RefreshAll
End Sub
Sub Button1_Click()
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")
Select Case password
Case Is = False
'do nothing
exit sub
Case Is = "Select15"
Range("A1").Value = "Code"
Case Else
MsgBox "Incorrect Password"
exit sub
End Select
For Each sh In Worksheets
If sh.FilterMode Then sh.ShowAllData
Next
ActiveWorkbook.RefreshAll
End Sub
You should exit the sub, if the password is not the correct one.
--^^
Or you can create a boolean bCorrect, to keep the result of the password and exit, if it is false.--v
Sub Button1_Click()
Dim password As Variant
Dim bCorrect As Boolean
password = Application.InputBox("Enter Password", "Password Protected")
Select Case password
Case Is = False
'do nothing
Case Is = "Select15"
bCorrect = True
Range("A1").value = "Code"
Case Else
MsgBox "Incorrect Password"
End Select
If Not bCorrect Then Exit Sub
For Each sh In Worksheets
If sh.FilterMode Then sh.ShowAllData
Next
ActiveWorkbook.RefreshAll
End Sub
Any value your user enters (except -1) is coded as "False", so your first case is being triggered. Check if the password is correct as your first option.

VBA hide sheets from specific users

Looking for some help on VBA User restrictions.
So far I have the code pasted below. It is working perfectly, but I want to build on it.
I have it so the specific users listed have access to the file, and anyone else who tries to access the file gets a msgbox saying they aren't authorized and then the book closes.
I am however hoping that some of the users can see some sheets (the sheets they shouldn't see will be xlveryhidden) And then the other users can see the other sheets listed...
ie:
Name 1 can see sheet 13,
Name2 can see sheet14 and sheet3
Name 3 can see sheet22 sheet23 and sheet4
In terms of security it isn't hugely important, they are all from the same team, but just for user friendly and tidy document.
Private Sub Workbook_Open()
Dim Users As Variant
Dim UName As String
Dim UFind As Variant
Users = Array("Name1", "Name2", "Name3", "Name4", "Name5")
UName = Environ("UserName")
On Error Resume Next
UFind = WorksheetFunction.Match(UName, Users, 0)
If Err <> 0 Then
MsgBox "You are not authorised to use this Workbook"
ThisWorkbook.Close SaveChanges:=False
End If
End Sub
Came up with an answer, it is pretty simple, and wont withstand new users being added, but for the mean time it is ok...
Private Sub Workbook_Open()
Dim Users As Variant
Dim UName As String
Dim UFind As Variant
Users = Array("Name1", "Name2", "Name3")
UName = Environ("UserName")
On Error Resume Next
UFind = WorksheetFunction.Match(UName, Users, 0)
If UName = "Name2" Then
Worksheets("Sheet23").Visible = True
Worksheets("SHEET17").Visible = True
ElseIf UName = "Name1" Then
Worksheets("Sheet23").Visible = True
Worksheets("SHEET17").Visible = True
Worksheets("Sheet4").Visible = True
ElseIf UName = "Name3" Then
Worksheets("Sheet23").Visible = True
Worksheets("SHEET17").Visible = True
ElseIf Err <> 0 Then
MsgBox "You are not authorised to use this Workbook"
ThisWorkbook.Close SaveChanges:=False
End If
End Sub
And in order to re-hide them all again when closing the file:
SubPrivate Sub Workbook_BeforeClose(Cancel As Boolean)
Worksheets("Sheet23").Visible = False
Worksheets("SHEET17").Visible = False
Worksheets("Sheet4").Visible = False
Worksheets("Sheet1").Visible = False
‘If you don’t save it’s not effective
Me.Save End Sub
Make changes in your If condition as:
If Err <> 0 Then
MsgBox "You are not authorised to use this Workbook"
ThisWorkbook.Close SaveChanges:=False
Else
For Each ws In Worksheets
If ws.Name <> "Sheet" & UFind Then
ws.Visible = xlSheetHidden
End If
Next ws
End If
Make sure that the sheet names are Sheet1, Sheet2, Sheet3, .. etc as mentioned in the question.

Add a new sheet using Input Box, check existing sheet names and invalid sheet names

Im new to VBA but i need to do something with it. I want to make input box that add a new sheet with specific name. somehow i can make it after some searching over the forum. here are the steps that i want to do, but i cant make it completely done.
make input box that ask a name of new sheet (it's done).
when the name of sheet is already available then a msg box appear
that it can't make a new sheet but when the opposite happen then a
new sheet is made (it's done too).
the last is i want to make when the input box is blank a new msg box
appear and ask to enter different name (this i can't do).
Here's the code im using so far
Public Sub CariSheet()
Dim SheetName As String
Dim shExists As Boolean
Do
SheetName = InputBox("Write the name of sheet", "Add Sheet")
If NamaSheet <> "" Then
shExists = SheetExists(SheetName)
If Not shExists Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = SheetName
MsgBox "The sheet " & (SheetName) & " is successfuly made", , "Result"
Else
MsgBox "The name is already exist, please enter a new name", vbOKOnly + vbInformation, "Name"
End If
End If
Loop Until Not shExists Or SheetName = ""
End Sub
Private Function SheetExists(ByVal SheetName As String, _
Optional ByVal wb As Workbook)
If wb Is Nothing Then Set wb = ActiveWorkbook
On Error Resume Next
SheetExists = Not wb.Worksheets(SheetName) Is Nothing
End Function
any help will be appreciated, thanks in advance for your attention. ah and sorry for my bad english.
Check if this code helps you:
Just added Else part for you Main If condition where you check If Sheetname is not blank.
Also, You can also uncomment my line Exit Sub if you want to exit subroutine in case of blank input box.
Public Sub CariSheet()
Dim SheetName As String
Dim shExists As Boolean
Do
SheetName = InputBox("Write the name of sheet", "Add Sheet")
If SheetName <> "" Then
shExists = SheetExists(SheetName)
If Not shExists Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = SheetName
MsgBox "The sheet " & (SheetName) & " is successfuly made", , "Result"
Else
MsgBox "The name is already exist, please enter a new name", vbOKOnly + vbInformation, "Name"
End If
Else
MsgBox "Please enter a sheet name.", vbOKOnly + vbInformation, "Warning"
'Exit Sub
End If
Loop Until Not shExists Or SheetName = ""
End Sub
This code caters for errors for either:
the sheet name already existing
the sheet name being invalid (empty (ie ""), too long or invalid characters)
Code updates so sheet name is validated for length, and then by a Regexp for Valid characters for Excel sheet names before the sheet is created
If either 1 or 2 is true the user is re-prompted (with an additional try again message)
Public Sub CariSheet()
Dim SheetName As String
Dim bFinished As Boolean
Dim strMsg As String
Dim ws As Worksheet
Do While Not bFinished
SheetName = InputBox("Pls enter the name of the sheet", strMsg, "Add Sheet")
On Error Resume Next
Set ws = Sheets(SheetName)
On Error GoTo 0
If ws Is Nothing Then
Select Case Len(SheetName)
Case 0
strMsg = "Sheet name is blank"
Case Is > 31
strMsg = "Sheet name exceeds 31 characters"
Case Else
If ValidSheetName(SheetName) Then
Set ws = Worksheets.Add(After:=Worksheets(Worksheets.Count))
ws.Name = SheetName
Else
strMsg = "Sheet name has invalid characters"
End If
End Select
Else
strMsg = "Sheet exists"
Set ws = Nothing
End If
Loop
End Sub
test for valid sheet name
Function ValidSheetName(strIn As String) As Boolean
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
objRegex.Pattern = "[\<\>\*\\\/\?|]"
ValidSheetName = Not objRegex.test(strIn)
End Function