Having issues using Select Case/Case Else logic to produce certain outcomes - vb.net

What I'm trying to achieve in my Windows form is to make my button compute a label output depending on calculated variables, but if the variable given in the textbox doesn't match what is listed in the code, a message box appears showing an error, and the label has a different output because of the failed match.
Here's some code to help further explain what I'm working with, and a description of the errors I'm receiving.
I have code that makes a variable, which finds the textbox that has numbers to substring the input and find the output:
Dim var1 As String
Dim Sb As String
Sb = Textbox1.Text
var1 = Sb.Substring(0, 3)
Then I'm placing that result to a label and trying to use it again to create the next label OR to show the messagebox saying there was an error using this code:
Select Case var1
Case var1 = "(result1)" Or "(result2)" Or "(result3)"
Dim var2 As String
var2 = "(Value)"
varlabel.Text = var2.ToString
Case Else
Messagebox.Show("Error occured, input not found.")
End Select
The issue I'm running into is that when I run the button's code, the first label will compute and publish successfully, but the second label will not publish correctly and will still show the message box even though I am giving it the correct input for the code to run. Can anyone shed light as to what I'm missing here?

This does not do what you want it to do:
Case var1 = "(result1)" Or "(result2)" Or "(result3)"
I can only assume that you haven't bothered to read the documentation for Select Case to even try that. It should be:
Case "(result1)", "(result2)", "(result3)"
ALWAYS read the documentation first if you have an issue.
https://msdn.microsoft.com/EN-US/library/cy37t14y(v=VS.140,d=hv.2).aspx

Related

Make Text Box visible with condition

I am new at VBA and I am trying some code and I could not find a solution or where I am doing wrong.
What I want: The combination of two different text boxes make another text box visible(so it starts in useform not visible). With one condition I could do it using select case(LLL) but when I try it with another variant it does not work(XXX). There is no error message, the code runs but does not show the text box.
Sub Visible()
If userform.TextBox5.Value = "XXX" And userform.TextBox10.Value = "245" Then
userform.TextBox1.Visible = True
userform.T_1.Visible = True
Else
GoTo LLL
End If
LLL:
Select Case True
Case userform.TextBox5.Value = "LLL", userform.TextBox10.Value >= "145"
If userform.Option000.Value = True Then
userform.TextBox1.Visible = True
userform.T_1.Visible = True
Else
userform.TextBox1.Visible = False
userform.T_1.Visible = False
End If
End Select
I understand some of your questions I must say that my code is quite big one cause it is linked to SAP in order to get some values from there and due to its size the complete code is splitted in modules and I am only sharing the module where I am facing problems.
There is one case for select case statement cause it was the only way that it worked close for what I need. I have a lot of variables for the fields TextBox5 and TextBox10 the values of these textboxes come from SAP and when I combine them, other Text Boxes shall be visible depending on the variables given. The problem is that for just one combination (this one is the one that I applied the select case statement) I need another variable (option000) so that TextBox1 and T_1 become visible. When I tried to do it only with if statements it did not worked.

vba - write text to sfile path does not work error

With the help of Userforms and textboxes, i can add new personnel to my personnel file, but there is something wrong in my code and the code does not work. I do get an error while carrying it out. The error says "Compile error: Method or data member not found". I dont know what is wrong with my code, my expectations are that i fill in some Textboxes and i want them added to the already existing seq file (Notepad). But it doesnt let me do that and i dont know why.
I would be happy if someone can find the problem and give a solution.
Thanks in advance.
If you need code from other Commandbuttons,Userforms,etc.. Please tell me.. I dont know entirely what to publish now.
I have already tried changing the Userform_Nieuw names, but to no avail.
Private Sub seq_bestand_maak_databank()
Dim diploma As String
Dim pad As String
pad = "C:\Users\fhaka\Downloads\Overzicht_Personeelsleden.txt"
If UserForm_Nieuw.OptionButton1.Value = True Then
diploma = "Secundair"
ElseIf UserForm_Nieuw.OptionButton2.Value = True Then
diploma = "Bachelor"
ElseIf UserForm_Nieuw.OptionButton3.Value = True Then
diploma = "Master"
End If
If CInt(nieuw.Label1.Caption) = 1 Then
Open pad For Output As #1
Else
Open pad For Append As #1
End If
Write #1, CInt(UserForm_Nieuw.Label1.Caption), UserForm_Nieuw.Voornaam, UserForm_Nieuw.Naam, CInt(UserForm_Nieuw.Aantal_kinderen), UserForm_Nieuw.Geboortedatum, UserForm_Nieuw.Startdatum, "---N/A---", diploma, "0", "---N/A---", "---N/A---", "EOR"
Close #1
End Sub
The goal is that the commandbutton works again and that i can add more personnel now.
The #1 part in Open pad For Output As #1 etc is a file handle. To obtain a file handle, you need to call FreeFile. You cannot just assume that file handle #1 is available at all times.
Try this:
Dim iOutputFile As Integer
iOutputFile = FreeFile
If CInt(nieuw.Label1.Caption) = 1 Then
Open pad For Output As #iOutputFile
Else
Open pad For Append As #iOutputFile
End If
Write #iOutputFile, CInt(UserForm_Nieuw.Label1.Caption), UserForm_Nieuw.Voornaam, UserForm_Nieuw.Naam, CInt(UserForm_Nieuw.Aantal_kinderen), UserForm_Nieuw.Geboortedatum, UserForm_Nieuw.Startdatum, "---N/A---", diploma, "0", "---N/A---", "---N/A---", "EOR"
Close #iOutputFile
It looks like you have not defined the method of the userform. You failed to compile and the highlight is on the UserForm_Nieuw.Voornaam. So I take that is some sort of input field for the first name? Check whether it is really called that or if it does no have the old default name (something like "Textbox275" or some such like your other elements, e.g. OptionButton1 and 2).

Excel VBA Match if value is null

I have a piece of code within a larger script that simply allocates a value to "i" based on a match. The idea being I want it to give the match value if the value entered is found, or 0 if not. If it's 0, I can then exit sub with a message to the user. However, any time the match finds a null value, it just kills the sub, instead of it being handled as part of the iferror I've introduced. I've tried various manners of checking (using iif(iserror) for example) but none seem to work.
Code causing the issue is below:
i = Application.WorksheetFunction.IfError(Application.WorksheetFunction.Match(username, EL.Range("A:A"), 0), 0)
i is dim as an integer
Username is dim as a string, and comes from an inputbox
EL is dim as a worksheet, and contains the correct info.
This has absolutely no issues if I introduce any name that exists, it only fails as soon as I input a name that does not work, and I'm sort of stumped as to why. I see no reason for it to fail, but feel like I'm missing something simply and in-my-face.
Use this instead. Using Application instead of WorksheetFunction enables the error to be trapped and tested.
i = Application.IfError(Application.Match(UserName, EL.Range("A:A"), 0), 0)
I would use a slightly different approach to trap an error on Application.Match function:
Dim i As Variant
i = Application.Match(UserName, EL.Range("A:A"), 0)
' if Match wasn't able to found a "match"
If IsError(i) Then i = 0

dr.Item("Value1") has value but always return 0 when assigned to another variable

I need to modify some VB.net code. There is a strange problem that I am facing. I am retrieving value from a DataTable and trying to assign it to a variable. When I check the value of some column in QuickWatch window then it has value but when I assign it to a variable then 0 is returned to the variable. Below is the simple statement that is causing the problem.
Dim MyAmount As Double = Double.Parse(dr.Item("Amount").ToString)
In the QuickWatch window when I check dr.Item("Amount") then it has value 30.12 and after executing the above statement MyAmount has value 0. May be VB.net work somewhat different that I do not know?
Edit:
It is kind of wierd that above mentioned statement is not returning value. The following statement is running absolutely fine.
Dim tmpVar As String() = dr.Item("Amount").ToString.Split(".")
Latest Edit:
I think it has become more wierd. The problem does not seem to be related with dr.Item("Amount"). Suppose I want to store the current culture value in a variable by following code,
Dim CultureInformation As String = System.Globalization.CultureInfo.CurrentCulture.DisplayName
Now CutlureInformation variable after the statement is executed contains "nothing" but the DisplayName has value of English (United States). So I think the problem is somewhere else.
You should be using this syntax:
Dim MyAmount As Double = dr.Field(Of Double)("Amount")
I am not sure why you are getting this behavior - your line should work too.
You can also try this:
Dim MyAmount As Double = DirectCast(dr.Item("Amount"), Double)
When facing a weird issue like this, always try various options to achieve the same result, do your research and compare the outputs. It greatly helps to answer a question on StackOverflow.

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.