What are a good No OP operation for vb.net? - vb.net

Something we can just put break point on while making sure it doesn't do anything else.
In c, that would be while(false);
What to do in vb.net?

If you always need it to break there you can put
Stop or Debugger.Break()

If you really want a No-Op for some reason (could this turn into a contest for the most ineffectual single line of code?!), how about these?
System.Threading.Thread.Sleep(1) - 1ms is unlikely to have a huge impact outside of a loop
Debug.Write("") - doesn't appear to output anything.

There is a legitimate use-case for this.
When a temporary breakpoint is required after the statement of interest and this is the last line inside an if statement, an extra no-op type statement is required to place the temporary breakpoint on.
In this case I use:
If someCondition >0 Then
doSomething
Space (1) 'Dummy line to place breakpoint
End If
This returns a string containing one space, but does not assign it to anything. I use it in VBA, but it's also supported in .net

My two cents...
You can combine any series of commands onto one line with colons:
If False Then : End If
Select Case False : Case Else : End Select
I've also made it into a sub. Then it gets a recognizable name of own:
'Definition...
Public Sub noop () 'Or Private, Protected, etc.
End Sub
'Usage...
Sub Main()
If sometest Then
noop
Else
MsgBox "test is false"
End If
End Sub

Very strange question, you could place a BreakPoint about anywhere in the code. But here are some useless lines :
Do While False
Loop
While False
End While
Even the following :
Dim hello = Nothing
Or this :
Format("", "")

A no-op statement is also useful as an aid to document code nicely and make it more easily understandable. You could for example put in a statement like A = A.
For example:
If MyNumber => 100 then A = A
Else:

I know this is an old query, but for what it is worth, my preferred solution to the original question is
Debug.Assert (vbTrue)
If you wanted, you could use a variable instead of vbTrue and then enable/disable all breakpoints in your code by changing one variable
Dim bDisableBreakpoints as Boolean: bDisableBreakpoints = vbTrue
'your code here
Debug.Assert (bDisableBreakpoints)
'rest of your code
Simply change bDisableBreakpoints to vbFalse and the breakpoints will be set wherever you have used Debug.Assert

My personal favorite is
dim b=1
Then I put a breakpoint there.

Related

Is there an equivalent of Python's pass statement in VBA?

I would like to know if there is an equivalent of Python's pass statement in VBA.
I am using Excel 2016.
The use of Stop (see this answer) seems to be the best thing to do if you are looking for some "non-statement" that you can use to insert a breakpoint, because the Stop command causes the code to break when it is reached, i.e. you don't even need to mark it as a breakpoint because it is one.
You might also like to consider using Debug.Assert some_logical_expression, which will break automatically whenever the logical expression evaluates to False. So Debug.Assert False would be equivalent to Stop, and Debug.Assert x = 3 would be equivalent to If x <> 3 Then Stop.
In Python you need the Pass, because otherwise the methods will not run.
In VBA, its perfectly ok if you leave an empty method like this:
Public Function Foo() As String()
End Function
Maby you are looking for the "Stop" statement.
The good thing about it is that it doesn't clear your variables.
It depends what are you trying to achieve.
You may declare a Label and then use GoTo Label e.g. declare a label (like Skip:)in your code where you want to jump if a condition is met and then use GoTo Skip
Below is the small demo code to give you an idea about this...
Dim i As Long
For i = 1 To 10
If i = 5 Then GoTo Skip
MsgBox i
Next i
Skip:

Suppress MsgBox from another Subroutine in VBA

I have a VBA sub that makes a call to a sub that was written by someone else. occasionally, the other sub opens a MsgBox with an OK button. The other sub takes a long time to run, and I am calling it hundreds of times, so I want to be able to run this overnight. Unfortunately, I can't figure out a way to automatically click OK on the MsgBox.
I have tried
Application.DisplayAlerts = False
but this doesn't suppress message boxes.
Is there any way to do this?
Thanks
One way to do this is slightly modifying the code of the original sub. You will need to have the necessary permissions tough...
Modify the header of the original sub by throwing in an extra optinal parameter at the end setting the default value to True. This will result in something like Sub OriginalSubName(original set of parameters, Optional ShowMessages = True)
At the point where the msgbox is called, modify the code this way:
If showMessages = True Then 'The = True part is important here - see below.
showMessages is a Variant type
'The original statement that calls the msgBox
End If
Leave the rest of the code of the original sub unchanged
Modify the line where you call the original sub by throwing in False as an extra parameter. This results in OriginalSubNameyour set of parameters, False. This way you don't suppress the dialog box by default, but you do when you use it in your sub.
Wonder why I use an optional Variant type parameter?
The optional part: this prevents other existing subs from crashing when they call the modified sub
The Variant type part: optional parameters are always Variant type. That's also why you need to use If showMessages = True Then instead of just If showMessages Then.

How do I use Do Until with a previous Try Catch Exception to avoid running the code twice

i have this line of code to catch an exception if a letter is inputed, or if it is out of rang as a number, but I have added WHEN to avoid catching numberical data. Now how can I use an exception error to use it before my case statement in order to avoid running the code twice, cause once the case codes has been through it will run a clear txtbox which is already taken care by the try catch, don`t if thats clear for you but i understand it. here is the code in parts...
Try
'Integer Levels: intLvls is egual to the assigned text box, the first one from
'the top, this line of code allow the user input to be captured into a variable.
intLvls = txtBoxLvl.Text
Catch ex As Exception When IsNumeric(intLvls)
ErrTypeLetterFeild1()
Finally
analysingvalues1()
End Try
WHAT I WOULD LIKE TO DO: Use loop until refencing the exception error to avoid running this following part of the code:
Private Sub analysingvalues1()
Do Until IsNumeric (ex As Exception)<------how do i do this???
Loop
the case part of the code:
Select Case intLvls
'User is prompt with the following label: lblLvl "Level of salespersons 1 - 4"
'to make a choice from 1 to 4 as available values.
Case 1 To 4
'This line regulates the range of acceptable values, first textbox: must be egual
'or higher than 1 and lower or egual to 4. Upon such rules a validation becomes
'correct and is directed to the isValidCalculation sub.
isValidCalculation()
Case Is < 1
ErrType1NumberRangeFeild()
Case Is > 4
ErrType1NumberRangeFeild()
Case Else
If txtBoxLvl.Text = "" Then
ErrTypeClear1()
Else
If Not IsNumeric(txtBoxLvl.Text) Then
ErrType1NumberRangeFeild()
Else
ErrTypeLetterFeild1()
ErrTypeClear1()
End If
End If
End Select 'Ending choices.
End Sub
Tks for your help!
If you turn on Option Strict this:
intLvls = txtBoxLvl.Text
Will no longer compile. This should tell you that your doing something smelly.
Turn on Option Strict
The correct solution is not to blindly allow the runtime to cast string to int for you, and catch the exceptions.
When you are converting string user input to an integer, bad input is not an exceptional condition, it is something you should expect and code defensively for.
I would rewrite it to something like this:
'Integer Levels: intLvls is egual to the assigned text box, the first one from
'the top, this line of code allow the user input to be captured into a variable.
if integer.TryParse( txtBoxLvl.Text, intLvls )
analysingvalues1()
else
ErrTypeLetterFeild1()
Edit - As pointed out by Chris below, I meant Option Strict. I recommend using but Explicit and Strict, and Infer if available.

Object reference not set to an instance of an object (Completely broken?) in vb.net

I know, I know, I could have used a for loop, dont tell me anything about that. Please, help!
Private Function LoadSaved() ''//Loads saved clippings if the user wants us to
Dim ZomgSavedClips As StringCollection
If IsDBNull(My.Settings.SavedClips) = False Then ''//If it is null this would return a rather ugly error. Dont want that do we?
ZomgSavedClips = My.Settings.SavedClips ''//ZomgSavedClips name was a joke, I just felt like it.
ZomgSavedClips.Add(" ") ''//This line ought to fix the error, but doesnt
i = 0
While i < ZomgSavedClips.Count ''//This is where the error occurs
ClipListings.Rows.Add(ZomgSavedClips(i))
i = i + 1 ''//First time I wrote this function I forgot this line. Crashed mah comp. Fail.
End While
End If
End Function
The line While i < ZomgSavedClips.Count is bugging, I know that the .count should return null but I even added a blank piece of text just to stop that. Whats up with this? Should I add actual text?
SavedClips is null no? If it is null it could pass the test IsDBNull beacuse the both are not the same
Obviously, My.Settings.SavedClips is still set to Nothing.
SavedClips is regular 'ole null (nothing in VB). Include a check for "My.Settings.SavedClips is nothing". If that evaluates to true then just leave the function.
I even added a blank piece of text just to stop that.
All you did was move where the error happens. You can't call .Add() on a null/Nothing object.
'''<summary>Loads saved clippings if the user wants us to</summary>'
Private Sub LoadSaved() ''//Loads saved clippings if the user wants us to
''//Load saved clips into memory
Dim ZomgSavedClips As StringCollection = My.Settings.SavedClips
If ZomgSavedClips Is Nothing Then ZomgSavedClips = New StringCollection()
''//Apply loaded clips to visible listings
Dim i As Integer
While i < ZomgSavedClips.Count ''
ClipListings.Rows.Add(ZomgSavedClips(i))
i += 1
End While
End Sub
Some notes on this code:
Don't use Function when you mean Sub
Since you'll be selling this code to others, you want to use xml comments at the top so that Visual Studio can give better intellisense helps.
IsDBNull() doesn't do what you think it does.
Yes, you should use a for loop, but since you already commented on that I left the while loop alone with the assumption that there's more code you didn't show us.

Syntax: "Exit Sub" or "Return" in VB.NET subroutines

Both "Exit Sub" or "Return" seem to accomplish the same thing -- exit a subroutine. Is there any difference in how they work under the covers?
That is,
Private Sub exitNow()
Exit Sub
End Sub
or
Private Sub exitNow()
Return
End Sub
From the doc:
In a Sub or Set procedure, the Return statement is equivalent to an Exit Sub or Exit Property statement, and expression must not be supplied.
So they're the same in this context.
(Return (<value>) is used in functions and property.get's. Obviously slightly different in that context).
I tend to prefer Return over Exit Sub. Because once in a while you change from Sub to Function. In this case Exit Sub could be converted to Exit Function, but this assumes that there was a previous assignment to the function name (alike VB 6), which most probably didn't happen. Return would catch this situation - if the method should return a value, Return with no argument will fail at compile time.
If you inspect the IL output of the 2 statements, they are the same. However, since ’return’ is meant for pushing something back to the caller, so strictly speaking, ‘Exit Sub’ is more suitable for using in a Sub.
They are the same in this context.
However, from the code readability point of view, "Exit Sub" would be clearer since the "Return" indicates that something some value is being used as an output (which is not the case with Sub-routines).
First of all, Procedures comes with sub, we should know that we are working on specific procedures that don't return a specific value with the ability of passing some specific parameters or even without passing any parameter. Such as:
Print something().
Calculate the factorial of integer number CalcFact(X).
Do some processes for a specific task.
Function is a specific process programmed to achieve a specific task by also passing some specific parameters, and it has to return some value that can be used to to complete the overall task, such as validation the user name and user pass.
In short Sub Doesn't return value and we call it directly "Print HelloWorld()" , whereas functions do such as:
ValidUsersNameAndPass("Johne","jOhNe13042019") ' This could return a Boolean value.
ValidUsersNameAndPass("Johne","jOhNe13042019"); // This could return a Boolean value.
I wanted to confirm that they act the same in lambda expressions too, and they do:
Sub test()
Dim a As Action = Sub() Exit Sub
Dim b As Action = Sub() Return
a()
b()
MsgBox("Yes they do!")
End Sub
While there are exceptions like guard clauses, in most cases I would consider either a sign that the method is too long.