Understand the pro and cons of the GoTo statement - excel

I'm working with excel vba since 3 month now and this is (after one course of programming in university) my first real contact to programming. Please take that to account.
I built up a userform with many textboxes. Therefore I wrote a makro which first checks if the user put in a value in every textbox so that afterwards the procedure begins. If there is not a value in every textbox I want the exit sub after msgbox the user to fill again every textbox. Quiet simple, right?
I thought the best way to manage this is using the Go to-statement. After showing my boss the code he told me I should never use this statement to avoid some sort of spaghetti code. He told me a real programmer would never use this statement and would try to work his way around. This is what my code looks like:
Private Sub SaveButton_Click()
Dim i As Integer
'mandatory textboxes:
For i = 1 To 13
If UserForm1.Controls("Textbox" & i) = "" Then: GoTo again
Next
'procedure...
Exit Sub
again:
MsgBox "Please fill in every mandatory textbox"
End Sub
My question: is it right to avoid this statement in every situation? Is it really some sort of unspoken rule to never use that statement? What are the Pros and Cons of this, and which are my alternatives(especially in this case)?
I appreciate every helpful answer. Thank you!

Your code can be easily re-written as below:
Private Sub SaveButton_Click()
Dim i As Integer
'mandatory textboxes:
For i = 1 To 13
If UserForm1.Controls("Textbox" & i) = "" Then
MsgBox "Please fill in every mandatory textbox"
Exit Sub
End If
Next
End Sub
Don't ever use GoTo unless it is behind On Error … or not avoidable. If there is any chance to avoid GoTo, then avoid it. It makes your code hard to maintain and is considered to be a bad practice.
As GSerg pointed out there might be rare cases where GoTo cannot be avoided. Eg. using GoTo for emulating missing language constructs (e.g. VBA lacks the Continue keyword) and exiting deeply nested loops prematurely.

Could be rewritten thus. So below the goto is replace by an Exit For and then a subsequent test. Avoid goto unless in an On Error Goto <lable> statement.
Private Sub SaveButton_Click()
Dim i As Integer
Dim bGut As Boolean: bGut = True
'mandatory textboxes:
For i = 1 To 13
If UserForm1.Controls("Textbox" & i) = "" Then
bGut = False
Exit For '* skip out
End If
Next
If Not bGut Then
MsgBox "Please fill in every mandatory textbox"
Else
'* start processing
End If
End Sub

Related

VBA: The use of GoTo for non errors

Just a quick question today, I am new to VBA and I am currently writing some code. In the code I use GoTo not for errors but just to write two different parts of functionality. For example the below:
Sub run_FetchTradeFilter()
Dim EntrySelection As Range
Set EntrySelection = Selection
[EntireTradeQuery].Calculate
If [CustomQuery] = True Then GoTo CaseCustomQuery Else GoTo CaseCustomList
CustomQuery:
'fill
'with
'ccde A
CustomList:
'fill
'with
'ccde B
EntrySelection.Select
End Sub
My question is, should I be using GoTo if its not for an error. Or should I be using an if statement or should I be using a SwitchCase?
Great, thanks to both for the clarification! Bets to avoid GoTo. Therefore I will write 2 separate functions and call them in the If statement

Open MsgBox if a date on birthday list matches today

Every time I try and execute my code it says "object required."
I want a MsgBox to open if one a date on my birthday list matches today.
The birthday list extends from b2 to b100 and I want to look through to find the birthday.
This is a piece of code I took from a YouTube video.
The MsgBox pops up every time I open the workbook.
Private Sub Workbook_Open()
Dim cl As Range
Set cl = ThisWorbook.Sheets("Birthdays").Range("B2:B100")
If IsDate(cl) Then
If Now >= cl Then
MsgBox "Somebody's had a birthday!"
End If
End If
End Sub
You are getting Object Required error because of a typo ThisWorbook should be ThisWorkbook
It is very normal to encounter such errors. So always use Option Explicit. I have covered it in To ‘Err’ is Human
So Can I have it added to my code automatically?
Yes you can. To have it added to all new files you create, simply select "Tools" -> "Options" in the VBE, and tick the "Require Variable Declaration" box.
Note: This will effect only new files that you create. You will need to add it yourself to existing files.
I basically just want my excel to create a msgbox when I open it, if one of the date on my birthday list matches today.
You can use Application.WorksheetFunction.CountIf to check if there is today's date in a range.
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Dim matchFound As Long
Set ws = ThisWorkbook.Sheets("Birthdays")
Set rng = ws.Range("B2:B100")
matchFound = Application.WorksheetFunction.CountIf(rng, Date)
If matchFound > 0 Then
MsgBox "Birthday Found"
Else
MsgBox "Birthday Not Found"
End If
End Sub
Screenshot
cl is a Range object representing 99 dalmatians cells, each encapsulating a Variant value.
The IsDate function is happy to take a Variant, but doesn't know what to do with 99 of them.
Because Range has a hidden default property, you can use it as if it were a value - but, especially for someone that's just beginning to learn VBA, it makes for confusing, implicit, "magic" code that says one thing, and does another.
If IsDate(cl.Value) Then
The implicit Range.Value member call here, yields a Variant representing the cell's value itself if the range represents only a single cell, otherwise (i.e. if the range is for more than one cell) it yields a Variant pointing to a 2D Variant array (in this case 99x1) that's holding every single value.
IsDate wants one value, so if we have 99 of them, we need a loop. But here's the thing: the last thing we want to do is iterate individual cells, get their Value, and verify that - because that would be very slow.
So instead, we grab that 2D Variant array, and iterate that.
If cl.Count = 1 Then
'single-cell range: not a 2D array
If Now >= cl.Value Then
MsgBox "Somebody's had a birthday on " & Format(cl.Value, "yyyy-mm-dd")
End If
Exit Sub
End If
Dim values As Variant
values = cl.Value
Dim currentRow As Long
For currentRow = LBound(values, 1) To UBound(values, 1)
Dim currentCol As Long
For currentCol = LBound(values, 2) To UBound(values, 2)
Dim currentValue As Variant
currentValue = values(currentRow, currentCol)
If IsDate(currentValue) Then
If Now >= currentValue Then
MsgBox "Somebody's had a birthday on " & Format(currentValue, "yyyy-mm-dd")
Exit Sub
End If
End If
Next
Next
Right now the msgbox just pops up every time I open the excel whether a birthday matches or not.
Sounds like your actual code has On Error Resume Next somewhere - that makes VBA ignore any run-time errors and merrily keep running, ...and you definitely don't want that. Rule of thumb, never use On Error Resume Next to side-step an error. Execution is normally halted when there's an "object required" error: an unconditional MsgBox popping means execution is allowed to continue in an error state, and that can't be a good thing.
As Sid found out, the type mismatch is caused by a typo -- this shouldn't be allowed to happen: make sure every module you ever type any code in says Option Explicit at the top, and it'll never happen again... for your early-bound code (late-bound code is still vulnerable to typos, but that's another story for another time).
Lastly, note that several of the above mentioned issues would have been reported by Rubberduck's code inspections (disclaimer: I manage this open-source project) - including the typo, the implicit default member calls, and the absence of Option Explicit.

Excel VBA - Using GoSub without Return

I have a situation where I'd like to use GoSub within a Subroutine and in some situations Return, but in others I would not have it Return. This will be in a large be For Loop and GoSub without Return could happen potentially hundreds of times. If I do not Return will this build up in memory and cause any issues?
I suppose my question boils down to: does GoSub stack? And will a large enough stack of un-returned GoSub's cause problems?
If it does stack, I can change the code to use GoTo in the instances where I do not want to Return, but for simplicity's sake I'd rather not.
Also thank you in advance for not lecturing me on GoTo/GoSub not being best practice :)
As plenty of others said: Don't do it. I am now programming (for a living) since 30 years and never had the need to use GoSub/Return except as a substitute when a programming language didn't provide any subroutines.
That said - I was curious about how VBA handles this. First thing: I assume that there must be a kind of stack. You can have multiple GoSub/Return in one routine and it is handled correctly:
Sub testSub1()
Call StrangeRoutine1
End Sub
Sub StrangeRoutine1()
GoSub L1
Exit Sub
L1:
Debug.Print "Strange1 - L1a"
GoSub L2
Debug.Print "Strange1 - L1b"
Return
L2:
Debug.Print "Strange1 - L2a"
Return
End Sub
This Prints:
Strange1 - L1a
Strange1 - L2a
Strange1 - L1b
So the return statements jumps after the correct GoSub - this is for sure handled with a kind of stack.
However, it seems that this stack is cleared once a Subroutine is left. The following routine has a GoSub, but no Return. So it leaves an open GoSub on the "stack". But when called a 2nd time and issues a Return without an GoSub, it throws an runtime error 3 "Return without GoSub`.
Dim count As Long
Sub testSub2()
For count = 1 To 2
Call StrangeRoutine2
Next
End Sub
Sub StrangeRoutine2()
If count > 1 Then Return
GoSub L1
Exit Sub
L1:
Debug.Print "Strange2 - L1"
End Sub
P.S.: Did i mention it: Don't do it!
The shortcut to see the stack in VBE is Ctrl+E. As you see it does not stack:
Sub GosubDemo()
GoSub MyRoutine
Debug.Print "Line before Exiting"
Exit Sub
GoSomeWhereElso:
Debug.Print "SomewhereElso I am "
Return
MyRoutine:
Debug.Print "My routine"
GoSub GoSomeWhereElso
Return
End Sub
However, do not use GoSub or GoTo in VBA. It is considered a very bad practice. GoTo could be used for Error Handling like On Error GoTo ErrorHandler.
GoSub ... Return MSDN
Dijkstra - GoTo considered harmful

Login attempts and error handling in VBA Excel

I have been trying to fix a login problem but I cannot find a solution. When both login and pass fail, an error message starts a countdown without letting the user manifest another opinion.
QUESTION 1: Can anyone please make the necessary corrections without altering too much the given code structure and explain?
QUESTION 2: What code would turn the "User1" text into bold at the moment the access is granted?
QUESTION 3: What command would disable the "X" on the top right-hand corner of the msg form?
Thank you in advance
Here it is what I could do
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
Private Sub BtOK_Click()
Dim User1 As String
Dim count As Integer
count = 3
MM:
If EDBoxlogin.Value = "admin" And EDBoxpass.Value = "1234" Then
User1 = Application.UserName
MsgBox "welcome" & User1 & " !", vbExclamation, "Access Granted"
Sheets("Plan1").Visible = xlSheetVisible
Unload Me
Else
If EDBoxlogin.Value = "" Or EDBoxpass.Value = "" Then
MsgBox "Please, fill in the fiels 'login' and 'pass'", vbExclamation + vbOKOnly, "Access denied : incomplete information"
Else
If count >= 0 Then
MsgBox "Login and pass are incorrect! You have " & count & " more trial(s)", vbExclamation + vbOKOnly, "Access denied"
EDBoxlogin.Value = "" And EDBoxpass.Value = ""
' I want to delete previous text in the editbox fields
count = count - 1
GoTo MM
Else
ThisWorkbook.Close
End If
End If
End If
End Sub
If you don't really need to know which user is opening the workbook, consider using Excel's built-in password security function. Also, you should encrypt the contents of the file also using Excel's built-in functions, or anyone can open the file with a text editor and find the userID and password listed in your code.
If you must use a login form, and I've also had to do so in the past, the following code builds on what you did by adding a user list to a hidden worksheet Users. Column A in that sheet needs to be the user names, B contains the passwords. This worksheet also uses cell D1 to track failed login attempts. Using variables in code for this sort of thing is tough ... you have to make them Public and if there are any errors when running code, it will lose its value, then bad things can happen.
The code also references another sheet, SplashPage. This allows you to hide Project1 when the user exits the workbook. The code I wrote handles the hide/unhide process when the file is opened or closed.
I don't know a way to turn off the close box in a user form. I've added code to reject the login if a user does that.
Happy coding.
'Module: frmLogin
Private Sub BtOK_Click()
Dim User1 As String
Dim Passwd As Variant
Sheets("Users").Range("D2").Value = False
User1 = EDBoxlogin.Value
Passwd = getPassword(User1)
If User1 <> "" And Passwd <> "" And EDBoxpass.Value = Passwd Then
Sheets("Users").Range("D2").Value = True
MsgBox "Welcome " & User1 & "!", vbExclamation, "Access Granted"
With Sheets("Plan1")
.Visible = xlSheetVisible
.Activate
End With
Sheets("SplashPage").Visible = xlSheetVeryHidden
Unload Me
Exit Sub
Else
Sheets("Users").Range("D1").Value = Sheets("Users").Range("D1").Value - 1
If Sheets("Users").Range("D1").Value > 0 Then
MsgBox "Login and pass are incorrect! You have " & Sheets("Users").Range("D1").Value & _
" more trial(s)", vbExclamation + vbOKOnly, "Access denied"
EDBoxpass.Value = ""
With EDBoxlogin
.Value = ""
.SetFocus
End With
' I want to delete previous text in the editbox fields
Exit Sub
End If
End If
UserForm_Terminate
End Sub
Private Sub UserForm_Terminate()
If Sheets("Users").Range("D2").Value <> True Then
MsgBox "Login cancelled, goodbye!"
doWorkbookClose
End If
End Sub
'Module: ThisWorkbook
Private Sub Workbook_BeforeClose(Cancel As Boolean)
doWorkbookClose
End Sub
Private Sub Workbook_Open()
On Error Resume Next
Sheets("Users").Range("D1").Value = 3
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
frmLogin.Show
End Sub
'Module: Module1
Function getPassword(strVarib As String) As Variant
Dim r As Long
Dim sht As Worksheet
Dim rng As Range
On Error GoTo ErrorHandler
Set sht = Sheets("Users")
Set rng = sht.Range("A:A")
r = WorksheetFunction.Match(strVarib, rng, 0)
getPassword = sht.Cells(r, 2).Value
Exit Function
ErrorHandler:
getPassword = Empty
End Function
Sub doWorkbookClose()
On Error Resume Next
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
End Sub
[begin Q&A]
Luiz, I've answered your edits below.
'Q: What Passwd does?
'Module: frmLogin
....
Passwd = getPassword(User1)
A: It gets the password value matching the value of User1. Here's the whole function for context:
Function getPassword(strVarib As String) As Variant
Dim r As Long
Dim sht As Worksheet
Dim rng As Range
On Error GoTo ErrorHandler
Set sht = Sheets("Users")
Set rng = sht.Range("A:A")
r = WorksheetFunction.Match(strVarib, rng, 0)
getPassword = sht.Cells(r, 2).Value
Exit Function
ErrorHandler:
getPassword = Empty
If User1 does not exist then WorksheetFunction.Match throws an error and code execution will jump to ErrorHandler:.
'Q: Does Empty mean that the cell is not with zeros or spaces, but completely blank instead?
A: Empty refers to a Variant variable type that is set to its default value. getPassword could just as easily return the boolean False or integer 0 because those are the default values for those types. It's actually not strictly necessary to set getPassword to anything here ... it's just my personal practice to be explicit.
Since IsEmpty(celFoo) is a valid test for whether a cell is empty or not, you might want to return False instead of Empty to avoid ambiguity.
'Q: Can you explain these two lines below in detail?
Set sht = Sheets("Users")
Set rng = sht.Range("A:A")
A: It's just habit. The alternative would be to elminate those variable assignments and rewrite this line:
r = WorksheetFunction.Match(strVarib, rng, 0)
as:
r = WorksheetFunction.Match(strVarib, Sheets("Users").Range("A:A"), 0)
which is messier to type. Especially if we're going to be doing other things on that sheet with that range in the same routine. Which we are in the next block of code ...
'Q: Important to explain these three lines below in detail too [why 0?, To where (r,2) points to?]
r = WorksheetFunction.Match(strVarib, rng, 0)
getPassword = sht.Cells(r, 2).Value
Exit Function
A: To review, worksheet Users contains user IDs in column A, and their passwords in column B. There can be as many users as there are rows in a worksheet.
- rng is column A as set above.
- 0 means find an exact match for strVarib and throw an error if not match is found.
- If we find a match, r will be set to the row number where the value in column A is equal to our input parameter, strVarib.
- So, sht.Cells(r, 2).Value is the password value in column B (column 2) for the UserID.
'Q: Why the need to call a splashpage? What it contains?
A: You don't necessarily need one, but if you really want to secure your workbook it's good practice. Let's say that it contains sensitive information that you don't want unauthorized user to see. At the very least you would:
Encrypt the worbook using native Excel functionality.
Password protect your VBA project using native functionality. This keeps savvier users from reading your code and making the xlSheetVeryHidden sheets Users and Plan1 visible to their prying eyes.
Now, you can't hide all sheets in a workbook at the same time, at least one needs to be visible at any given time ...
... so I've created a third sheet called SplashPage that doesn't contain any sensitive information. And that means I can hide all of the other worksheets until the user enters a valid UserID and password in frmLogin.
SplashPage can contain whatever you want. You can call it whatever you want. Typically, mine says something like:
Welcome to the Enemies List Application!
Only authorized users may access this workbook.
If you're seeing this page and no login form is visible
it means you've disabled the macros in this workbook.
Please make sure macro security is set to "Medium"
then close Excel entirely, reopen this file
and select "Enable Macros" when prompted.
If you attempt to view or modify this file without proper
authorization you will be added to the list herein.
-[Signed] Richard M. Nixon
A really really secure workbook would not contain the users and passwords in a hidden sheet. In fact, I never do this. Most of my apps are database driven, and I authenticate users against both the domain and a custom table in the application database. This effectively keeps anyone from using it unless they're onsite and connected to the network. I also usually flush all the data from the relevant worksheets when the user closes the workbook to a) keep the file size smaller and b) keep sensitive data from being stored in it and taken offsite. But that's beyond the original scope of your question.
'Why is [the following] necessary? What is being saved? Purpose?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Save
A: There are two scenarios for closing the application: 1) a failed login attempt and 2) a successful login by a user who has finished making changes.
Take case (2) first. We want to hide all the sensitive information before closing so that the next person who opens the file only sees SplashPage and the login form. We know the user is closing the workbook because we have this code in the ThisWorkbook module BeforeClose event script:
'Module: ThisWorkbook
Private Sub Workbook_BeforeClose(Cancel As Boolean)
doWorkbookClose
End Sub
All it does is call this subroutine in Module1:
Sub doWorkbookClose()
On Error Resume Next
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
End Sub
Since our close routine makes changes to the workbook to hide sensitive information, those changes need to be saved. If ThisWorkbook.Save wasn't there, Excel would prompt the user if they wanted to save "their" changes. Which is annoying at best, confusing at worst, because most users will have already pressed "Save" before closing. And if we give them the option here now to close without saving, then we run the risk of all those sensitive worksheets we've just made xlVeryHidden visible to the next user. And that next user could be a bad guy who knows how to disable macros (or anyuser who simply has macro security set above Medium) which means that the following code wouldn't run:
Private Sub Workbook_Open()
On Error Resume Next
Sheets("Users").Range("D1").Value = 3
With Sheets("SplashPage")
.Visible = xlSheetVisible
.Activate
End With
Sheets("Plan1").Visible = xlSheetVeryHidden
Sheets("Users").Visible = xlSheetVeryHidden
ThisWorkbook.Save
frmLogin.Show
End Sub
which is my semi-paranoid-self trying to make it as sure as possible that the next user opening this file doesn't see something I don't want them to.
Note that none of this secuity is bomb-proof. It will lock out most average Excel users that you don't want in it, but someone who knows more about VBA than I do could probably find a way in.
Yes, that was an invitation. :)

vba error code in form

hey, first thanks to all for answering my other questions. I am extremely new to Excel VBA and some things I just get hung up on. I have a userform (not embedded in a worksheet) and I have a few fields that are for currency (amounts, etc) and if someone inputs a letter it errors after they hit the command button and they lose all info. I need error code to where I can tell them in a msgbox that they should not put characters in a currency field. I don't need it specific to those fields but I don't want them to lose there data when they hit the command button to dump the data into a spreadsheet.
How can I have them see the error msg, hit the ok button and have it take me right back to the screen without losing the data they have alread entered? Basically give them the opporunity to correct their error but not have to reinput 50 fields?
Thanks
Can't be specific without the actual code, but add error handlers to your code:
Sub SomeRoutine()
Dim stuff
On Error GoTo EH
' Code
Exit Sub
EH:
' Any errors with come here
If Err.Number = <specific errors to trap> Then
MsgBox "Oops..."
'As a debug tools, put a Resume here,
' but be sure to put a break on it,
' and don't leav it in the finished code
Resume
End If
End Sub
As I understand it you want the user to enter numeric numbers only into the text box - right? This is what I normally do.
In a global module add the following function:
Function IFF(c, t, f)
Dim v
If c Then v = t Else v = f
IFF = v
End Function
Then in your textbox_change event add the below:
Private Sub txtAmount_Change()
txtAmount.Text = IFF(IsNumeric(txtAmounto.Text), Val(txtAmount.Text), 0)
End Sub
This will basically put 0 in the box as soon as the user enters an invalid number.
Hope this helps
A slightly different take on error handlers than that given by chris neilsen
Sub SomeRoutine
On Error GoTo ErrHandler 'doesn't matter where you put it
'as long as it's before the code you want to protect
'Dim Stuff
'Do Stuff
ExitRoutine: 'Note the colon(:), which makes this a label
'Any cleanup that you _always_ want
Exit Sub
ErrHandler:
Select Case Err.Number
Case <some error you want to handle specially>
'special handling
Case Else
'default handling, which may include:
Resume ExitRoutine
End Select
Resume
End Sub
Note that that last Resume will never get hit in normal processing (if you've written your error-handling Cases correctly), but will let you set it as "Next Statement" when you're debugging in Break mode. This is an easy way to see exactly which statement threw the error.

Resources