Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.
Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.
Click the categories below to get started!
Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial
If you like a tutorial, please use the "digg" button below it.
In this tut I will be using images to help you see whats happening. It also makes for less writing ;) So start a new Visual Basics Program with a Standard Forum. Resize it to About the same as my image[just for no reason]
Image of Layout
Now that you have that, to create a menu you can Right Click on the Forum and Click the Menu Editor... button, or look on top for the same icon and click it. [highlighted in read box]
Now you have a window to work with the menu the editor looks like this.
This works the same as making a command button or a label. Enter the caption that you want to be displayed, for example 'File' now Name it, same as a label , this one would be named 'mnuFile' Okay there are Four Arrows, Next, Insert and Delete Buttons. The four arrows are used for moving, or adding a 'sub menu Next Button is to move on to adding the next menu button Insert is for adding a menu about the Item you have highlighted, Delete, deletes what you have selected. Okay lets make 4 menu buttons, File | Edit | About | Help
Click the |Edit| Menu button you created in the text box, and then click Insert, you will see it will make an open slot between File and edit. Now click the Right Arrow, this puts '....' This will create either a button Under File lets name it Exit, it should look like this
Lets click okay should look something like this.
Now these work just like anything else, if you double click it, you can add the code you want to it. :) Have fun with your menus!
While you can also check to see for a running process (which is better for those programs like MSN Messenger that run in the quick launch bar), simply finding a window is easier and often used as a validation method.
Now, let's begin.
You will need the following for this project: 2 Command Buttons - One named cmdclass and the other named cmdcaption
The caption for the cmdclass button is Class while the caption for the cmdcaption button is Caption.
First, you have to declare an API that you plan to use, which in this case is the FindWindow API. It goes like this (put this in a module):
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
The public part of the above code means that this function can be carried across your forms. In other words, if you put this function in a module, then go to Form1, you will be able to input it. Switching public to private reverses this effect, so a private function can only be used in the form it is declared in.
So now we have declared the API, but we must now declare a variable to store this function in. Let's name it find. Put this at the very top of your form:
Dim find As Long
The next step is finding a window to locate. What window shall we choose? Let's go with the most basic of all, notepad. There are two methods to find the notepad window. By class name or by the window name. The class name of notepad is: Notepad The window name of notepad is: Untitled - Notepad Assuming you have an untitled file.
Now, what's the difference?
Class names are often a more secure way to locate a window. Why? Well, whenever you open a file in notepad, the caption of the window changes to the name of your textfile - notepad. An example, "MyTextFile - Notepad" This makes it rather difficult to keep track of notepad with a changing caption, so class names should be used in this case, because they always stay constant.
Let's begin with class names:
Double click on the class button and put this in:
FindWindow(Notepad, vbNullString)
Don't like class names? Then let's try the same approach with captions.
Double click on your caption button and put this in:
FindWindow(vbNullString, "Untitled - Notepad")
Ok, that's a complete bit o` code, or is it? How do you know it actually "found" the window, it doesn't give you any feedback. Let's add some message boxes to let us now it actually found what we told it to find. Under your cmdclass button, edit your code to make it look like this:
find = FindWindow("Notepad",vbNullString) If find <> 0 Then MsgBox "I found the window by class name!", vbOkOnly, "Window found." Else MsgBox "I can't find the window!", vbCritical, "Window not found." End If
Under your cmdcaption button, edit your code to make it look like this:
find = FindWindow(vbNullString,"Untitled - Notepad") If find <> 0 Then MsgBox "I found the window by caption!", vbOkOnly, "Window found." Else MsgBox "I can't find the window!", vbCritical, "Window not found." End If
Now hit F5 in the Visual Basic IDE and try it out! ;)
The full code looks like this:
Module:
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Form:
Dim find As Long Private Sub cmdclass_Click() find = FindWindow("Notepad",vbNullString) If find <> 0 Then MsgBox "I found the window by class name!", vbOkOnly, "Window found." Else MsgBox "I can't find the window!", vbCritical, "Window not found." End If End Sub Private Sub cmdcaption_Click() find = FindWindow(vbNullString,"Untitled - Notepad") If find <> 0 Then MsgBox "I found the window by caption!", vbOkOnly, "Window found." Else MsgBox "I can't find the window!", vbCritical, "Window not found." End If End Sub
Before we make the program, I am going to break down the syntax of If's. They are quite easy when it comes down to it. You always tell the program that you are going to start a new if by going to a new line and typing "If"...that wasnt to difficult. If's basically check to see if a certain condition is true and then executes a block of code.
ElseIfs check to see if the above condition is true and then test the same thing with another condition. Else simply states that if the above isnt true, then do this. This is how an if statement would be set up:
If object.value is {True, False, or a mathmatical expression}
Then What the program does if the above is true Else What the program does if the above is not true End if You must always end an if or your program will result in errors.
Ifs are also neat in the fact that they can be nested, meaning ifs within ifs. Just dont forget to close any ifs you open.
Alrighty, now lets apply it. Open a new Visual Basic project, standard EXE. Set the form name to frmIf and the caption to "Im learning IF's." Add the following elements: Labels > lblAdd Command Buttons > cmdExit; cmdTest Text Boxes > txtAnswer Set the command button captions to Exit and Is it Right?.
Set the label caption to 2 + 2 = and the Text property to the text box to nothing. Double click cmdTest and open up an If. Now, we want to check to see if the text in txtanswer is equal to 4. If it is, then display a message box that tells the user they are right, else if it is not, display a message box that tells the user they are wrong. Dont forget to end the if.
Your code should look like this:
If txtanswer.Text = 4 Then MsgBox "You're right" Else MsgBox "You're wrong" End if
Simple when it comes down to it. I will be writing a more complicated version with more in depth descriptions and tings to do at a later date.
For now, try and make a program with a label that asks someone their age and if the number is greater than 17, a message or label says that they are an adult and if they arent, the label says that they arent.
Good luck and happy programming.
The Visual Basic Development Environment
The Visual Basic environment is a very easy and user friendly one. Everything is easy to get to and easy to use. Here is a screenshot of the VB Environment.
Tool Box: Here you will find all the necessary objects for making the user interface of your program. Form Window: This is where you will design your forms/applications
Tool Bar: The toolbar allows you to hide/show any of the pannels one of the pannels Form Location: Lets you know where about on the screen your form will display Form Size: Lets you know how big your form is (in twips)
Project Explorer: This is where all files associated with a certain project are displayed, whether it be modules, forms or ActiveX controls.
Properties Window: This is where you can control the appearance and usability of objects such as forms and controls from the Tool Box
Form Layout Window: An easier way to determine where your form will be displayed on a users monitor
The Visual Basic Tool Box
Thats it. Nothing to complicated. If someone writing a tutorial refers to a control you are unsure about or a window you are unsure about, just refer back here.
Timers are not necessarily only used for something like a stop watch. They can be used to control how often a loop executes or the value of a string of text, integer or a boolean.
Set up
Open Visual Basic on your computer and start a new standard EXE project. Save now if you wish. Name your form frmWatch and set its caption to Basic Stop Watch. When completed, this program will be able to start the watch, stop it, reset it and record a lap time. You will need the following objects on your form: * Command Buttons (4) o cmdStart - Used to start the timer o cmdStop - Used to stop the timer o cmdReset - Used to reset the timer/form o cmdLap - Used to execute the code that will record the current time to a text box * Textboxes (1) o txtLap - Used to store the data from the current lap time * Labels (2) o Label1 - Static label, set caption to \"Current Time\" o lblTime - Used to store the current time elapsed * Timers (1) o tmrNew - Used to time
You can place the timer object anywhere on the form as it will not be visible to your users. You can place the rest of the objects any which way, so long as it makes sense... Now we begin to code. The first thing we want to do is click the tmrNew object, scroll to the interval property in the properties window and set it to 100. This means that the timer will execute every 10[sup]th[/sup] of a second. If you set it to 500, it will execute every half second, 1000 will execute every second, etc etc....Also set the enabled property to false because we dont want the timer going off right when the program is loaded. Now double click the timer to bring up the code window for tmrNew.
We need to declare one variable. This variable is going to be used to store and dynamically change the data it holds every time the timer executes. After declaring your variable, we need to set it equal to the value of lblTime's caption. This may seem useless for the start, but this is how we get our 0 to begin with. Now we need to auto increment the value of our variable by 0.1 (or 1/10[sup]th[/sup]) of a second.
If you used any other interval for the timer, you may need to change the number from 0.1 to whatever number fits your interval. The last thing to do is set the caption of lblTime's caption to the data in the variable, but we are going to want to format it for display purposes. Use the below code if you are lost:
Dim sngClock As Single sngClock = Val(lblTime.Caption) sngClock = sngClock + 0.1 lblTime.Caption = Format(sngClock, \"###.0\")
The next thing on our agenda is to start and stop the clock. The bulk of this project is out of the way, the rest of the actions are all executed by one line of code in each procedure (except Reset, a whole three lines). Double click your cmdStart button and add code to enable the timer (tmrNew.enabled = true). Double click your cmdStop button and add code to disable the timer (tmrNew.enabled = false). Double click your cmdResetButton and add code to clear the values of lblTime and txtLap.
Now add code to disable the timer just in case the user clicks Reset before clicking stop. For the final bit, double click your cmdLap button and add code to add the value of lblTime's caption to a new line in the text box. All the code for the aforementioned procedures can be found here:
Private Sub cmdStart_Click() tmrNew.Enabled = True End Sub Private Sub cmdStop_Click() tmrNew.Enabled = False End Sub Private Sub cmdLap_Click() txtLap.Text = txtLap.Text & lblTime.Caption & vbCrLf End Sub Private Sub cmdReset_Click() tmrNew.Enabled = False lblTime.Caption = 0 txtLap.Text = \"\" End Sub Private Sub Form_Load() tmrNew.Enabled = False End Sub
Run the program and play with it. You're done!
Message Boxes
You tell the program you want a message box using the following: msgbox There are many options used in a message box, the table below lists the different button set ups and different icons to display on the message box.
Now you may be wondering how you apply all these fantastic features to the message box. The syntax layout below should explain that pretty well. msgbox "prompt", button, "title", help file, context We will only be using the first three (prompt, button, title) because I dont know how to use the other two :D. Anyways, its pretty simple, in the area it says prompt, you put in what you want it to say. For button, you put in any of the options from the above table (button or icon) exactly as it appears (IE; vbOkCancel) and then you put the title. Make sure things that are displayed in quotes stay in quotes.
Alrighty, now that we have covered that, Im going to show you how to use a message box. Not very hard at all. For now, just create a new form. Form name and project name do not matter for this particular tutorial. Double click the Command Button in your tool box to add a command button to the form. Name it cmd1 and set the caption to Message Box Now we get to coding. Double click cmd1 to open up the click event procedure sub in the code window. Add the following code. msgbox "Hey, you clicked my button" , vbvbExclamation, "You clicked it!" Thats all there is to it.
Now Im going to make it a little more complicated. Before you continue on, make sure you are pretty comfortable with variables and familiar with If statments as they are used a bit here in the next few steps.
Alright, erase what you coded for the command button. Add a textbox to the form and name it txt1, and set the text property to nothing. Once that is done, open up the code window and make sure you are under click event procedure for cmd1. Declare some variables. dim strMsg as string dim strStyle as string dim strTitle as string See anything familiar.
What we are going to do is change the values of those variables to alter the display of our message box based on what a user inserts. Alright, now for the If statement. Put the following code under the variable declerations. if txt1.text >= 5 then strmsg = "The number was more than 5" strStyle = vbInformation strTitle = "More than 5" else strmsg = "The number was less than 5" strStyle = vbCritical strTitle = "Less than 5!!!" End if Now, that will do absolutley nothing, so we need to have a message box pop up. Add this under the if statement. i = MsgBox(strMsg, strStyle, strStyle) There is a bit of a difference here between the regular decleration and this one. When using variables in your message box, you must set it equal to another vairable and nothing can be in quotes. This works best if you just use a one letter variable, undimmed, and have it at the end of the coding for that event procedure. You see how that works? Simple enough.
Quick Tip:
You can use multiple button/icon combos by doing this: MsgBox "Hey", vbInformation + vbOKCancel, "Titled" Notice the added plus sign?
Input Boxes
An input box is different from a message box in the sense that it asks the user a question and leaves a text field for the user to type in. Input boxes are a bit more complicated because must have a variable associated with them or they serve no purpose. You can have one just pop up, but the information the user puts in will not be saved anywhere.
The syntax layout below explains how to customize your input boxes: inputbox("Prompt", "Title", "Default", Xpos, YPos ,Help File, Context) Again, we will only worry with the first three. Prompt is basically what you want to ask the user. The title is the title of the input box and default is the default text already in the text box. The only required attribute is Prompt, the rest you don't need. Now onto making something useful.
Start a new form, again, form name and caption do not matter, same with project name. Make a label in the middle of the form. Get rid of the caption and name it lblOutput. Time for some code. Double click the form to bring up the code window for the sub form load event procedure. We need to declare one variable, and that is to store the data the user types in. dim strPets as string Now, on a new line, insert the following: strpets=inputbox("How many pets do you have?","My Survey","Enter Number Here") Simple enough, not complicated.
Next we need to display the data. On a new line, type this lblout.Caption = "You have " & strpets & " pets!" So our entire event procedure looks like this: Dim strpets As String strpets = InputBox("How many pets do you have?", "My Survey", "Enter Number Here") lbloutput.Caption = "You have " & strpets & " pets!" Play it and see what happens. Nifty, huh? Well thats it for this tutorial. Good work if you completed it. If you have any questions, post below.
Tutorial Challenge:
Create a form that asks a user how old they are and displays the age on a form. Then make a command button that when clicked, an alert pops up and asks if they are sure they want to quit. Hints: vbOkCancel, put the message box before End in the CmdExit click procedure.
By default, VB will name elements based off of what they are, ie: the first label you put down is named Label 1, and the second is Label 2; same goes for command buttons and all other items in the tool box. (See Tool Box)
Keep in mind that you can name these things what ever you want, but in my tutorials I will be using correct naming structures. It is best if you know them for when you learn to make mroe advanced programs in the future. They help organize them and make coding your programs much much easier.
For the following, "Name" constitutes what you want to name the object.
* Form Level
o Form
+ frmName
* Tool Box
o Picture Box
+ picName
o Label
+ lblName
o Text Box
+ txtName
o Frame
+ fraName
o Command Button
+ cmdName
o Check Boxes
+ chkName
o Option Buttons
+ optName
o Combo Boxes
+ cmbName
o List Boxes
+ lstName
o Scroll Bars
+ hsbName for Horizontal and vsbName for Vertical
o Timer
+ tmrName
o Drive List Box
+ drvName
o Directory List Box
+ dirName
o File List Box
+ filName
o Shape
+ shpName
o Line
+ linName
o Image (there is a difference between Image and Picture Box)
+ imgName
o Ole Client
+ oleName
* Menu
o Menu
+ mnuName
* Variables (See Variable tutorial for more info)
o String
+ strName
o Integers
+ intName
o Currency
+ curName
o Boolean
+ blnName
o Byte
+ bytName
o Date
+ dteName
o Double
+ dblName
o Single
+ sngName
o Long
+ lngName
o Object
+ objName
o Variants
+ varName
Please make sure you have an understand in select case before moving on, otherwise you will be typing rubbish that you don't understand. The first new topic we will learn in this tutorial is the command Randomize. Obviously this command has one purpose, to make things random. Use Randomize to initialize VB's random number generator. This is called seeding. To avoid generating the same sequence of psuedo-random values, call Randomize before you call Rnd; but this only has to be done once. A good place to seed the psuedo-random number generator is in the Form's Load event:
Private Sub Form_Load() Randomize End Sub
Alright, for this tutorial, make a program with one text box and one command button. Name the command button cmdRandom and add a caption that says Randomize!. Now, for the text box, name it txtText and set the text property to nothing.
Double click the command button. The purpose of this program is going to be to generate a random number between 1 and 6, simulating the roll of a dice. The first thing we need to do is to write the statement for which the Select Case will be checking. This is done with a variable, usually a simple, one letter, undeclared variable. But in this variable, we are going to tell the program to generate a random number between 0 and 5. The reason we are starting at 0 is because all Programming languages start counting at 0.
x = Int(Rnd * 6)
That basically is saying that x is equal to a random number times 6, the random number being what the select case is going to output. Now we open our select case with the following:
Select Case x
We need to call 5 case statements, each with a different number and each setting the text of txtText to a new number. We start with this
Case 0 txtText="1"
All you do is repeat that 5 more times, chaging the two numbers to the next real number in line (0, 1, 2, 3,4..) The last thing to do, as with any program you have opened up a function, is close it. Close the Select Case with End Select
All in all, you should have a procedure that looks like the following:
x = Int(Rnd * 6) Select Case x Case 0 txtText = "1" Case 1 txtText = "2" Case 2 txtText = "3" Case 3 txtText = "4" Case 4 txtText = "5" Case 5 txtText = "6" End Select
Although simple, this tutorial was only written to touch on the Randomize and RND functions in Visual Basic, to help shed some light on them and further your understand about the concepts, not to write a simple program.
Throughout this tutorial I will use TheString to represent a string. Imagine it declared as this:
Dim TheString as string
The String = "Just some text stored in a string"
For some of the VB.NET examples I will use a different type of variable. It is a StringBuilder. The deceleration is such:
Dim StringB as New System.Text.StringBuilder()
StringB.append( "Just some text stored in a stringbuilder")
A string builder is much more efficient when changing the value of a string and much more feature rich. For more on why I used append here read the section on append. To return a real string from the StringBuilder you need to call the .ToString method:
MsgBox(StringB.ToString)
Almost all of the examples use a message box to display the results. Pasting the sample code and the decelerations into the load part of a form should render a working example.
Len or Length - Getting the length of a string
To get the length of the string in VB6 you would use the Len() function.
MsgBox(Len(TheString))
That will return 33 because TheString is 33 characters long.
In VB.NET you would use the .length property.
MsgBox(TheString.length)
This would also 33 because TheString is 33 characters long.
Mid or Substring - Returning part of a string
Using this method you can extract a string, a substring, from anywhere inside another string. In VB6 the Mid() function would normally be used (there are two others, Left() and Right(), but I will get to those latter).
MsgBox(Mid(TheString, 6, 4))
That will return "some". You told it to start at the sixth character and continue for the next four. The mid function works like this:
Mid(String, StartCharacter [, NumberOfCharacters])
For VB.NET you use the .substring method.
MsgBox(TheString.substring(5, 4))
If you noticed your probably wondering why I used 5 this time instead of 6. Well in VB.NET you start counting at 0 in a string, another step closer to the C languages. :P
Replace - When you have something you just don't want as is
This method is relatively simple. You give it a string to find and a string to replace the first string with. VB6 with Replace():
MsgBox(Replace(TheString, "text", "characters"))
The response from that should be "Just some characters stored in a string". VB.NET has little changes to it.
MsgBox(TheString.replace("text", "characters"))
This will also return "Just some characters stored in a string".
UCase or ToUpper - Making the text 'loud'
To change the case of some text to upper case or all capitals use the UCase() function.
MsgBox(UCase(TheString))
With the above code you would get "JUST SOME TEXT STORED IN A STRING". VB.NET with .toupper:
MsgBox(TheString.ToUpper)
Another way to get "JUST SOME TEXT STORED IN A STRING".
LCase or ToLower - Quiting down that 'loud' text
This is identically to UCase in VB6:
MsgBox(LCase(TheString))
With that you'd get "just some text stored in a string". The VB.NET method is also identically to .toupper:
MsgBox(TheString.ToLower)
Same as before "just some text stored in a string".
StartsWith - Matching the start of a string
This method has no VB6 equivalent, it is only available in VB.NET. This is general used in an If.
If TheString.StartsWith("Some") then
MsgBox("The string starts with 'Some'")
End If
That would return "The string starts with 'Some'".
EndsWith - Matching the end of a string
This method has no VB6 equivalent, it is only available in VB.NET. This is general used in an If.
If TheString.EndsWith("string") then
MsgBox("The string ends with 'string'")
End If
That would return "The string starts with 'string'".
Left or Substring - Getting the start of a string
This method has no true VB.NET equivalent, though substring replaced it. In VB6 you would use it as such:
MsgBox(Left(TheString, 4))
That would return "Some". In VB.NET you use the substring method and tell it to start at 0:
MsgBox(TheString.substring(0, 4))
This would also return "Some".
Right - Getting something from the end of a string
Just like Left, this method has no true VB.NET equivalent. You could through the use of .length and .substring avoid the use of this function but it's more work then you should need to do. VB6 with Right():
MsgBox(Right(TheString, 6))
This would return "string". In VB.NET you need to qualify the Right function because the Form object now has a Right property.
MsgBox(Microsoft.VisualBasic.Right(TheString, 6))
It's about twice as long as the VB6 example but does the same thing. I thought the .NET framework would make things easier? :P
Append - Adding on to a string
This function is only available to VB.NET using a stringbuilder. Append adds text to the string builder. A string builder does not allow assignment by use of an equal sign (=) so you must use the .append method to assign the initial value.
MsgBox(StringB.append(" object"))
Since StringB already contained the value of "Just some text stored in a stringbuilder" this would return "Just some text stored in a stringbuilder object".
StrReverse - gnirts a gnisreveR (Reversing a string)
This is a VB6 function. I have not found an equivalent VB.NET function.
MsgBox(StrReverse(TheString))
This would return the very confusing string of "gnirts a ni derots txet emos tsuJ".
Concat - Stick to string together
Well the VB6 verison of this is very simple and (in my opinion) much easier then this VB.NET function. VB6:
MsgBox(The String & " object")
That returns "Just some text stored in a string object". In VB.NET you could do this:
MsgBox(String.Concat(The String, " object"))
This returns the same as the much shorter and still useable in VB.NET VB6 code.
Split - When you need to separate some things
The split function is normally used to separate a comma (or other symbol) delimited list into an array. I'm not 100% sure this VB6 example is completely correct so don't think it's all your fault if you try it and it doesn't work.
Dim CSVlist as string
CSVlist = "part1|part2|part3|part4"
Dim CSVarray() as string
CSVarray = Split(CSVlist, "|")
That should set CSVarray to the following values:
CSVarray(0) = "part1"
CSVarray(1) = "part2"
CSVarray(2) = "part3"
CSVarray(3) = "part4"
In VB.NET you would use this:
Dim CSVlist as string
CSVlist = "part1|part2|part3|part4"
Dim CSVarray() as string
CSVarray = CSVlist.split("|")
This should have the same output as the VB6 example.
StrConv - Special string conversions
VB6 has some special string conversions. You can format a string so it is proper case. Proper case meaning the first letter of every word capitalized. This has no VB.NET equivalent.
MsgBox(StrConv(TheString, vbProperCase))
This would return "Just Some Text Stored In A String". You can replace vbProperCase with vbLowerCase for lower case conversion or vbUpperCase for upper case conversion.
Join - Reversing the splitting
Join can be used to reverse what split has done. It can take the members of an array and turn them in to a comma (or other symbol) delimited list. VB6:
Dim CSVarray() as string
CSVarray(0) = "part1"
CSVarray(1) = "part2"
CSVarray(2) = "part3"
CSVarray(3) = "part4"
Dim CSVlist as string
CSVlist = Join("|", CSVarray)
This should set CSVlist to a value of "part1|part2|part3|part4". The VB.NET version of this is:
Dim CSVarray() as string
CSVarray(0) = "part1"
CSVarray(1) = "part2"
CSVarray(2) = "part3"
CSVarray(3) = "part4"
Dim CSVlist as string = String.Join("|", CSVarray)
Trim - Cutin' off that white space
To remove extra white space (spaces) from the start and end of a string use the Trim() method in VB6.
Dim AString as string
AString = " Spaces "
MsgBox(Trim(AString))
This would return "Spaces". In VB.NET you'd use this:
Dim AString as string
AString = " Spaces "
MsgBox(AString.Trim)
LTrim, RTrim, TrimEnd, and TrimStart - Selectivly removing white space
LTrim and .TrimStart both remove white space from the start. VB6:
Dim AString as string
AString = " Spaces "
MsgBox(LTrim(AString))
This would return "Spaces ". In VB.NET you'd use this:
Dim AString as string
AString = " Spaces "
MsgBox(AString.TrimStrat)
To remove white space from the end use RTrim in VB6 and .TrimEnd in VB.NET.
InStr, InStrRev, IndexOf, and LastIndexOf - Finding the location of a substring in a string
These functions are used to find how many characters into a string a substring is found. VB6:
MsgBox(InStr(TheString, "text"))
This should return 11 because the t of text is 11 characters into the string. In VB.NET use the .indexof method.
MsgBox(TheString.IndexOf("text"))
To find the last occurrence of a substring in a string use the InStrRev function in VB6 or the LastIndexOf method in VB.NET.
Insert - Adding a string in
I am unaware of a VB6 equivalent though one may exist. In VB.NET you would do it as such:
MsgBox(TheString.insert(15, "and some more text "))
This should return a string of "Just some text and some more text stored in a string"
Format
Do to the large amount of information that I would need to dicuss to properly cover the format function it will not be discussed now.
Well I think I have covered enough for now. If you want a quick summary of everything covered here is a list of the VB6 and VB.NET equivalents:
This tutorial is marked as an intermediate tutorial. Please make sure you know and understand the following things: * Variables (using and declaring) * If, IfElse and Else statements * Message Boxes * With Blocks We will start by making the following form: Project name: Validate Form Name: frmValidate
Alright, now that we have our form set up, lets get the easy coding out of the way. Double click the "Exit" button and insert the following code block for the click event procedure: end Close out of the code window. Now, double click the "Execute" button to open the code window. Make sure you still on the click event procedure. I’m going to put the entire code right now, and then break it down in the next few steps. Insert the following code (don't copy and paste, you do not learn that way)
for the click event procedure of
cmdExecute Dim strname As String Dim sngage As Single If txtname.Text = "" Then MsgBox "Enter your name", , "Missing Data" txtname.SetFocus Exit Sub ElseIf IsNumeric(txtname.Text) Then MsgBox "Numerals are not allowed in the text box, enter your name.", , "Invalid Data" With txtname .SelStart = 0 .SelLength = Len(txtname.Text) .SetFocus End With Exit Sub Else strname = txtname.Text If txtage.Text = "" Then MsgBox "Enter a number greater than zero", , "Missing Number" txtage.SetFocus Exit Sub ElseIf Not IsNumeric(txtage.Text) Then MsgBox "Enter numerals and no other characters", , "Invalid Data" With txtage .SelStart = 0 .SelLength = Len(txtage.Text) .SetFocus End With Exit Sub ElseIf IsNumeric(txtage.Text) And Val(txtage.Text) <= 0 Then MsgBox "Age must be greater than zero", , "Age Out of Accepted Range" With txtage .SelStart = 0 .SelLength = Len(txtage.Text) .SetFocus End With Exit Sub Else sngage = txtage.Text End If End If lbloutput.Caption = "Hello " & strname & ". You are " & sngage & " years old."
Press play and you will see the following types of errors: * If you don’t enter your name or age, you receive an error. * If your name contains numbers, you will receive an error * If your age is less than zero, you will receive an error
Alright, now for the synopsis. I will break down the above code, block by block. The first thing we do is declare the variables we will be using. Most times I will declare my variables in General Declarations (See Variable tutorial), but this time, since they are only local variables, I will declare them in the event procedure for cmdExecute. Dim strname As String Dim sngage As Single We have told the program we will be using one "string" variable and one "single" variable.
Next we begin validating the information the user puts in. The first if block is checking whether or not txtName is empty or not. If it is, an alert pops up (see message box tutorial) telling the user they forgot to fill out a field. The user clicks okay, and the cursor is automatically placed in the Name field. With the "elseif" statement, we are saying: if the above is true, then check this. We are checking to see if txtName holds any numerical data. We do this by utilizing the isnumerical() function. If this turns out true, the same thing happens as before, except this time we have used selstart and sellength to highlight the data in the textbox.
The next thing we are doing is saying that if the data entered into the txtName text box is not numeric and not invalid, then set strName equal to the text in txtName. Now we begin validating the information in the age text box. The first step is the same as before, check to see if the text box is empty. It is done the same way as was done with the txtName field. Now we check to see if txtAge is not a numerical value. This is accomplished by placing a “not” before the isnumerical() function: elseif not isnumerical(txtage.text) then If the data entered in txtAge is not a number, then an alert box notifies the user they must enter a number, greater than zero, into the text box.
Now that we have determined whether or not the info in txtAge is a number, we must determine whether or not this number is negative. You can’t be -13 years old, can you? We need to use another elseif. We tell the program that if txtage is a number and if that number is less than or equal to zero, display another alert box notifying the user they need to enter a number greater than zero. If all of the above criteria are met for txtAge, then we finally tell the program to set sngAge = txtAge.text. We must now close our If statements. Remember, we have opened two if statements, which means we need to close two if statements. If you don’t, it will result in errors. Now the last thing to do is set the caption of lblOutPut to display: “Hello {name}. You are {age} years old.”
Good work, I hope this helped you better understand how to validate data with VB.
Most programs require the temporary storage of data. The data is stored in a variable, which is a temporary storage in the computer's memory.
The variable name is the "identifier", used to identify the data. Variables names must begin with a letter and comprise a series of alphanumeric and '_' up to 255 characters in length.
Visual Basic 6 does not require that a variable be declared before use, but this is a dangerous practice and can lead to logical errors that are difficult to detect. In order to force variable declaration, specify Option Explicit in General Declarations.
Scope and Duration
The scope and duration of a variable is determined by the keywords Dim, Redim, Public, Private and Static. You can declare a variable anywhere in the body of the code, but it is good practice to declare all of your variables in the beginning. Refer to the below table for information on Scope and Duration.

Data Types of Variables
There are different types of variables for different types of data in Visual Basic. They range from dates, true and false, small numbers, large numbers, etc. The data type is determined by the "As" keyword. If the "As" keyword is ommited, VB will default to the "Variant" data type. The table below illustrates the types of variables, examples, and their uses:
Declaring Variables
Declaring a variable in VB is quite easy. You simply combine a Scope and a Data type with a name. dim strMyVar as string You can also Dim multiple variables on one line, but often times people forget to specify a data type, forcing VB to default to Variant type. dim intX as integer, inty as integer, intz as integer
Well that is basically all there is to it. If you have any questions, simply post in here. Not to difficult, but variables are a must in most programs.
Start and Setup
Open Visual Basic and select new Standard EXE from the menu that appears, or if that does not appear, then select File -> New Project from the menu. Click "Project1 (Project1)" in the Project Explorer. Look in the Properties Window. Click where it says Project1 next to Name. Change it to MyFirstProgram. You can only use alpha-numerical characters and underscores (_) when naming Projects. Now, click the + next to "Forms" to expand your form explorer. If it is already done, you're a step ahead :). Click Form1 (Form1) and do what you just did with project, except name it "frmMyFirstProgram" Simple, eh? Now we need to add a caption to our program. Go to Caption in the Properties Explorer and set it to "My First Visual Basic Program." You can use any ascii character when stating a caption, although sometimes they require a special code (like in HTML, to display © you would write ©)
Making Controls and Customizing Them
Now that we have the basics done for our Form, we will start making controls. The end result of this program will be two text boxes where the user inserts two numbers in each box and clicks a button. The program adds the numbers and the answer displays in a text box after an equals sign. Our program will require the following controls: * Text Boxes (3) o txtNum1 o txtNum2 o txtAnswer * Labels (3) o lblPlus o lblEqual o lblInstruct * Command Buttons (2) o cmdAdd o cmdExit For all the text boxes, set their text property to blank. For txtAnswer, set the appearance to "Flat", border style to "none" and backcolor to "button face". Set the visible property to false. It kind of looks like a label now, doesnt it? For lblPlus, make the caption +, for lblEquals, make the caption =, and for lblInstruct, set the caption to: Insert a number in each of the text fields, and click add to get the answer. For cmdAdd, make the caption Add! and for cmdExit, make the caption Exit. Thats it for the controls, make your form look something like this:
Now we can begin the programming part.
The Coding
To open up the coding window, you can right click in the white area and choose View Code or you can double click any object on the form, or the form itself. To start, double click on Exit. It brings up our click event procedure for the Exit command button. Type this in: End. That is quite possibly the simplest piece of code in VB. Run the program by clicking the play button at the top. Click Exit and you see that the program closes. That was easy. :) Now, double click on Add!. This is where it can get confusing for a extreme beginner, but just follow with me because it is really easy. You should have this shown in front of you right now:
What we want to do is take the text in txtnum1 and add it to the text in txtnum2. This is a very simple code, but will explain a lot in the workings of Visual Basic. The first code you want to add is the core of the program. Normall, we would stop here, but I am going to introduce you into some other aspects of Visual Basic. Make the code for cmdAdd_Click() this:
Run the program by clicking the play button at the top and enter in two numbers in the two text fields and click Add!. It gave you the correct answer. Congrats, we have the brain of our first program. But What If the User Does'nt Put in a Number If the user does not put in a number, it will cause an error. This is easy to detect and fix. Stop the program and erase the code you just added for cmdAdd_Click().
We are going to be using an if statement. Ifs basically check to see if a condition is true or not true and then display something based on the results of that check. For this instance, we are going to check to see if the text entered in the two text boxes are numbers, and if they arent, we will display an error message. The first thing we do is open up our if by typing If. Now we need to tell the program what we are checking. In this case, we are checking to see if the text in txtNum1 and txtNum2 is numerical or not. Immediatly after our If, type IsNumeric(txtNum1.text) and IsNumeric(txtNum2.text). To tell the program we are done stating what we want it to check, you type Then and hit enter. Now, in this area is what we put if the condition we stated above is true. For this program, we put what we had before. Your code block should look like this:
Now we move onto telling what the program what to do if the condition was not true. We accomplish this by writing Else on a new line. Hit enter again to start a new line and this is the area we add what we want the program to do if the condition was false. Same as what we did before in theory, but not in code. For this program, we are going to add a message box. This is accomplished by using MsgBox (this is a preinstalled function with Visual Basic). Message Boxes are quite easy to use, and can get quite elaborate in design, but for the purposes of this program, I am only going to make a simple one. Once the user hits "OK" on the message box, we want to send them back to the text field with the error. This is accomplished by writing txtNum1.setfocus. Once this is done, we can end our if statement by writing End If. Mimick my code:
You can make the message box say whatever you want.
Conclusion
Well that is basically it, your first Visual Basic Program. A very easy tutorial to follow. Please post if you have any trouble. Good luck with your VB Future.
Challenge
Create a program that either subtracts or multiplies two numbers together. Make sure you check to see if the user enters in a number. Upload and post your programs in this thread. Good luck.