You are on page 1of 19

Guida - Visual Basic

Mirë se vini në tutorialin e Visual Basic. Visual Basic (ose VB) është një gjuhë
programimi e zhvilluar nga Microsoft që shkon me .Net Framework. Me Visual Basic
ju mund të ndërtoni aplikacione për Windows, aplikacione të internetit dhe
aplikacione telefonike të Windowsit. Programet e zhvilluara në Visual Basic do të
funksionojnë vetëm në një Sistem Operativ të Windowsit. Visual Basic është i lehtë
për të mësuar, argëtues dhe i fuqishëm!

Tutorialet e meposhtme testohen të gjithë me Visual Studio 2010/12/15/17 dhe


përdorin .NetFramework 4. Versioni 4.6 do të jetë në gjendje të mbështesë
.NetFramework 4.

Visual Basic - Instalimi


Për të instaluar Visual Basic ju do të duhet Visual Basic Express IDE. Mund të duhen
deri në një orë ose dy për ta shkarkuar dhe instaluar atë, varësisht nga shpejtësia e
internetit dhe fuqia e kompjuterit tuaj.

Visual Studio IDE


Këtu me poshte është një përmbledhje themelore e Mjedisit të Zhvillimit të
Integruar të Visual Studio 2012 (IDE). Ne nuk do të hyjmë në një analizë të thellë
të IDE-s, thjesht do te paraqesim një pasqyrë të shkurtër të artikujve të nevojshëm
per te punuar me te.
Faqja startuese

Sponsored Links

Kjo me siper është faqja e startimit të IDE-s: Në të djathtë është një paleta e
mjeteve dhe në të majtë janë projektet tuaja të fundit dhe projekti "Projekti i ri" si
dhe "Projekti i hapur". Në krye është një shirit standard i menusë.
Dritarja New Project

Kjo është dritarja e Projektit të Ri: Në të majtë ju keni instaluar gjuhët dhe në mes
keni modelin e tipit te programit qe do te zgjidhni per te ndertuar(Windows, web,
etj.). Shënim: Ju do të shihni vetëm Visual Basic nëse jeni duke përdorur edicionin
e shprehur. Ne do të bëjmë Aplikime ne Console në .Net Framework 4.0.
Hapesira e punes - WorkSpace

Më siper është hapësira e punës tuaj: Ky është një aplikacion me konsole. Ju keni
hapësirën tuaj të punës (ku shkruani kodin) dhe dritaret e gabimeve tuaja. Ju do të
shihni në hapësirën e punës se keni numra të rreshtit te shkruar me kode. Për të
shfaqur numrat e rreshtit, shkoni te Tools> Options> (expand) Text Editor > VB> në
anën e djathtë> Display, Line Numbers.

Shënim: Visual Studio IDE ndryshon shpesh, sigurohuni që të qëndroni të azhornuar


me përditësimet e tyre të softuerit. Ju gjithashtu duhet të lexoni edhe dokumentacionin
qe shoqeron versionin e ri per ndryshime te mundshme.

Permbledhje
Visual Studio IDE ka shumë funksione dhe ne ju rekomandojmë që të luani rreth tij
për të njohur veten. Ne do të përdorim vetëm disa nga këto karakteristika; në fakt
ne do të krijojmë vetëm Aplikacionet e Konsolisë kështu që do të ketë përdorim të
kufizuar të veçorive të përparuara.
Visual Basic - Sintaksa

Visual Basic ka një sintaksë shumë të thjeshtë të programimit. Gjuha nuk është e
ndjeshme ndaj çështjeve dhe është projektuar për njerëz të rinj në botën e
programimit, duke e bërë atë një mundesi të mirë për të filluar.

Shkoni përpara dhe filloni një aplikim të ri ne VB Console dhe jepini emrin Sintaksa.
Ju duhet të shihni kodin e mëposhtëm:

Module Module1

Sub Main()
End Sub

End Module

Kodi juaj duhet stuar në mes te instruksioneve Sub Main () dhe End Sub. Në VB,
linjat nuk përfundojnë me një pikepresje ; krahasuar me C ++ dhe shumicën e
gjuhëve të tjera, VB është i thjeshtë!

Komentet ne VB

• Komentet lineare vetem ne nje rresht fillojnë me një apostrof (')

• Nuk ka komente bllok në VB

• Komentet XML fillojnë me tre apostrofë; këto janë të dobishme për qëllime
dokumentimi

Organizimi i Kodeve
Organizimi i kodit është shumë i rëndësishëm, si dhe komentet dhe grupimi i
kodeve janë shumë të dobishme. Konsiderohet praktikë e mirë grupimi dhe
komentimi i kodit kështu që zhvilluesit e tjerë mund të punojnë në të. Komentet
duhet të japin një përshkrim të vogël të asaj pjese të kodit dhe grupimet janë
përdorim i dobishëm i kodeve së bashku. Për të krijuar një grupim ose rajon
“region” ju përdorni sintaksën e mëposhtme:

#region "emri i rajonit"

Te tjera kode vendosen ketu..


#End Region
Kjo do të demonstrohet më tutje në mësimet e mëvonshme.

Shkrimi i Programit te pare


Tani eshte koha per te shkruar te parin program ne VB. Gjithcka vendoset mes fjaleve celes Sub
Main() dhe End Sub si me poshte:
Console.WriteLine("Programi I pare ne Visual Basic!")

Console.ReadLine()
Shtyp F5, ose butonin Start dhe ka per tu shfaqur:

Programi I pare ne Visual Basic!

Console.WriteLine eshte nje metode e sistemit.

Shenja e pikes (angl. dot) quhet edhe Member Accessor (aksesues I anetarit)

Organizimi i skedareve te programeve


When you build your program, certain files are created. It may seem excessive, but they are
actually just simple files and instructions for your program and the Visual Studio IDE. Navigate
to C:\users\<yourname>\ Documents\Visual Studio\Syntax (or the saved file
location). Find the file called Syntax.sln and a folder called Syntax. If you open the Syntax.sln
(sln is a Visual Studio Solution file) with notepad, you will see it has some global settings; we
advise you not edit anything!
In the Syntax folder there will be 3 folders: obj, My Project and bin. There will also be two
files: Module1.vb and Syntax.vbproj. The Module1.vb is our source code for our program.
Next, open up Syntax.vbproj, which is a Visual Basic Project File. This is actually an XML file
which stores information about other file locations; do NOT edit it.
Now open up the bin folder; inside is another folder called debug which is where your program
will output. If you double click Syntax.exe the program will run. Go back and open up the My
Project folder, and focus on the file called AssemblyInfo.vb. This stores information about the
program such as author, copyright, trademark, etc.

Permbledhje
Visual Basic has a very simple programming syntax. Most of the code is easily understandable,
even if you are not familiar with programming. The language is not case-sensitive, inline
comments start with an apostrophe, and XML comments start with 3 apostrophes

Variablat ne Visual Basic


Variables allow us to store and retrieve data. Variables are storage locations and the data is held
in the computer's memory (RAM). In Visual Basic, variables start with the Dim keyword.

Syntax
Dim <variable name> As <data type>
VB supports a number of data types; the common ones are:

Sponsored Links

Tipi I te dhenave Pershkrimi

Integer Numrat e plote

Single Numrat dhjetore me nje shifer pas presjes psh. 5.2

Boolean True ose False

Double Floating Point numbers but more accurate

Char Single characters

Variables can start with uppercase or lowercase characters.

Create a new VB Console Application and name it Variables. Between the Sub Main() and End
Sub, type the following:
Sub Main()

Dim myNumber As Integer


myNumber = 5

Console.WriteLine(myNumber)
Console.ReadLine()

End Sub
Hit F5 or click the green play icon on the toolbar. You should see the result 5.

Code Explained
 First we use the Dim keyword to create the variable myNumber
 Next we assign the value 5 to myNumber
 We then use the Console.WriteLine command to print out myNumber
 Finally, we use Console.ReadLine to read that line
String Variables are wrapped in quotation marks; comment out the above code, highlight it all
and press CTRL+K+C (to un-comment, CTRL+K+U). Next, type the following:
Dim name As String

name = "Asim"

Console.WriteLine(name)
Console.ReadLine()
This should print out Asim. This code works the same as above, but this time it was a string
data type. You can also add, subtract and perform other mathematical calculations. Under the
above code, write the following:
Dim x As Integer
Dim y As Integer

x = 32
y = 15

Console.WriteLine(x + y) 'Add x (32) and y(15) ( 32 + 15


= ?)
Console.ReadLine() ' ReadLine
You should get the value 47. This time we made two integer variables called x and y, assigned
them a value, and then added them together.

Summary
 Variables start with the Dim keyword

 Variables can start with uppercase or lowercase characters

Visual Basic Strings


 Strings are enclosed in double quotes ( " " )

 Strings are a data type

 Strings are a collection of characters

Syntax
Dim stringName As String

Example
Here are several ways in which you can manipulate strings. Create a new VB Console Application
and name it Strings. Next, type the following:
Sponsored Links
Sub Main()

Dim myName As String


myName = "thecodingguys"

Console.WriteLine(myName)
Console.ReadLine()

End Sub
Press F5 to debug and you should see the text thecodingguys. This is a simple string.
Comment out the above code (CTRL+K+C).

Escape Character
In cases where you need to escape quotation marks which get in the way, see the following
example:

Dim text As String

text = "Asim Said: "Hello World" "

Console.WriteLine(text)
Console.ReadLine()
If you run this (F5), you will get an error saying End of Statement Expected. The problem is
that VB thinks that the line ends at "Asim Said:", which is incorrect. So what we need to do is
put four double quotes around Hello World, as such:
Dim text As String

text = "Asim Said: ""Hello World"" "

Console.WriteLine(text)
Console.ReadLine()

Output
Asim Said: "Hello World"

New Line
When you need a new line, in C# the new line is simply \n; however in VB it is quite different.
Comment out the above code and put this below:

Dim newLine As String


newLine = "This is a new" & vbCrLf & "Line"
Console.WriteLine(newLine)
Console.ReadLine()
This time we use the keyword vbCrLf to make a new line. Put your first line code in one
quotation then your second in another, and in between put & vbCrLf &

Concatenation
Concatenation means joining two things together, in this case joining strings. It can be very
useful when you want to link something together to form a sentence. You use the & ( or + ) to
form a concatenation. For example:

Console.WriteLine(myName & " is awesome")


This will print out "thecodingguys is awesome". myName is a variable we created earlier.

String.Format
The string.format method is useful for formatting your text, and you can format it in many ways.
For example, say you wrote Console.WriteLine ("Your balance is £5"); however, if you gave
this away to someone in the USA or Italy, they would see the British pound symbol instead
of their own country's currency symbol. This is where the .Net Framework becomes useful, as it
can detect the user's country / regional settings and format the piece of text to match
those settings.

Example
Dim myNumber As Double = 158

strFormat = String.Format("{0:C}", myNumber)


Console.WriteLine(strFormat)

Console.ReadLine()
Now when you debug this (F5) you should see it print out 158 with your country's currency
symbol in front of it. For more ways to format strings, see the table below:

Format Description

{0:C} Currency Symbol

{0:P} Percentage Symbol

{0:N} Thousand Separator


The 0 in the format key specifies the parameter you want to format, followed by a colon and
then the formatting type.

Example 2
This time we use two parameters.

Dim myNumber As Double = 158


Dim mySecondNumber As Integer = 25

strFormat = String.Format("{0:C} {1:P}", myNumber,


mySecondNumber)

Console.WriteLine(strFormat)
Console.ReadLine()
In this example, the first parameter (myNumber) would appear as £158 and the second one
would appear as 25%.

Manipulating Strings
There are many built-in methods available to you, so you can format strings in a number of
ways. For example, you can format a string and make it all uppercase, you can remove spaces,
or you can simply count the length of the string. In the next few examples, you will see a few
useful methods used to manipulate strings.

In the following examples we will be working with a string called yourMessage which will have
the text “Welcome to thecodingguys”, and another string finalResult which is set to nothing.

Dim yourMessage As String = "Welcome to thecodingguys"


Dim finalResult As String = Nothing
For the sake of brevity we have omitted the Console.WritelIne(finalResult), from the examples;
however if you want to add it, remember to add the Console.ReadLine() as well.

ToUpper and ToLower


The ToUpper and ToLower converts a string either to uppercase or lowercase format.

Example
finalResult = yourMessage.ToUpper()
finalResult = yourMessage.ToLower()
Replace
The replace method replaces a string with another string. It takes two parameters, the old string
and new string, and it can also take chars. In the following example, the spaces in yourMessage
are removed and replaced with dashes.

finalResult = yourMessage.Replace(" ", "-")

Output
Welcome-to-thecodingguys

Substring
The substring method can be used to return parts of a string. For example, from the
yourMessage string we can return the first 5 characters only. The substing method takes two
parameters: the start index and length index as integer.

Example
finalResult = yourMessage.Substring(0, 7)
The 0 specifies the start point, in this case it is at the beginning; the 7 specifies how many
characters we want from the starting point. To get all the characters you would do as follows:

finalResult = yourMessage.Substring(0, yourMessage.Length)

Output
Welcome

Exceptions: Watch out for the ArguementOutofRangeException,


which is common. This occurs when the string length is shorter than
the points specified; for example if 0, 25 was used, it would give
that exception as yourMessage is only 24 characters long.

Count
The count and length method return the length of the string.

finalResult = yourMessage.Count()
There are many more methods available.

Method Description Output


Contains See if a string contains a certain piece of text Reutrns boolean (either true of false)

StartsWith See if a string starts with a certain piece of text Boolean - true of false

EndsWith See if a string ends with a certain piece of text Boolean - true of false.

Summary
In this tutorial we showed you how to format and manipulate strings in Visual Basic.

 New Line is vbCrLF


 Escape Character ""
 String.Format followed by {0:C} or N or P. (The String.Format Full List is available at MSDN
Library VB String Formats)
 Functions: ToUpper, ToLower, Replace, Substring, etc.

Visual Basic Dates And Times


Dates and times are also another data type in Visual Basic. Sometimes you may need to print
out the date in your application or web application, like for example when a post was last edited.
There are many ways you can manipulate dates and times in Visual Basic, and we will discuss
the most common ones. Create a new VB console application and name it Dates And Times.
Then between Sub Main and End Sub() put the following code:
Console.WriteLine(DateAndTime.Now)
Console.ReadLine()
This will output the date and time as such:

17/07/2012 19:39:06
This will print out the date and time according to your PC. One thing you should bear in mind is
that since this is based on the .Net Framework, the date and time will print out depending on the
format the computer uses and the time zone you are in. The above code simply prints out the
current date and time.

Getting the date


Here we will just focus on getting the date and then format it in several ways. We will do the
same as before, but this time we will say Date.Now. Copy the following:
Console.WriteLine(Date.Now.ToLongDateString)
Console.ReadLine()
This prints out the date in a long format; it will not print out the time as we have not told it to.
We can also print "short date" by using ToShortDateString. Try removing the ToLongDateString
and replacing it with ToShortDateString, or simply copy the following:
Console.WriteLine(Date.Now.ToShortDateString)
This will output 17/7/2012.

Extract date
Here we will get just the month and day on their own. Since the date will be displayed as an
integer, we will need to convert it to a string and format it; for example:

Console.WriteLine(Date.Now.DayOfWeek)
Now this surprisingly outputs 2 (meaning Tuesday ), because Tuesday is the second day of the
week. However, if you want the word "Tuesday" you need to format it. What we do is write
Day.Now.ToString(format) as follows:

Console.WriteLine(Date.Now.ToString("dddd"))
This will print out the current day. You can do the same for month by putting MMMM instead of
dddd (case-sensitive). Getting the year is also quite simple; we use this code:

Console.WriteLine(Date.Now.Year)
This will print out the current year. Now we are going to focus on the AddDays Method,
which adds days to the current day. For example, today is 17/07/2012. If you wanted to know
what the day will be in 30 days, you would write:

Console.WriteLine(Date.Now.AddDays(30))
If today is 17 July 2012, in 30 days it will be 16 August 2012. This also works for AddHours,
AddMinutes, AddYear, AddSeconds and so on.

Getting the time


Next we will get the time on its own. We repeat the same process as when we got the date, but
this time we will use ToLongTimeString:

Console.WriteLine(Date.Now.ToLongTimeString)
This will print out the current time, and it will print out the hours, minutes and seconds. You can
also use the ToShortTimeString method; this will only get the hour and minute. You also
may want to get the time in a 12 hour clock format. To do this:

Console.WriteLine(Date.Now.ToString("hh:mm:ss tt"))
This gets the time in 12 hour format, and also displays AM or PM.

Extract time
Like the date we can also extract the time and get the hours and minutes on their own. The
process is basically the same as above.

Hour
Console.WriteLine(Date.Now.Hour)
This will simply get the hour, no minutes or seconds.
Minutes
Console.WriteLine(Date.Now.Minute)

Seconds
Console.WriteLine(Date.Now.Second)
As before, we can also add on hours, like in the following example:

Console.WriteLine(Date.Now.AddHours(10).ToLongTimeString)
You can also get the minutes and seconds as before. In this example, after we have given the
hours to advance by (which is 10), we also add which time format we want. This is necessary,
because without it, it will print out the date and time.

Method / Property Name Description

Prints out the day in the following format 17 July 201


ToLongDateString
2

ToShortDateString Prints out the date in short format 17/7/2012

Gets the current time in the format HH:MM:SS (Hour


ToLongTimeString
s, Minutes, Seconds)

Gets the current time in the format HH:MM (Hours an


ToShortTimeString
d Minutes)

Now Gets the current date and time

Day Gets the current day as integer

Year Gets the year

Month gets the month as integer

DayofWeek Gets the day of the week as integer

Hour Gets the current hour

Minute Gets the current minute

AddHours Adds hours to the current time

AddDays Adds days to the current day


AddMonth Adds months to the current month

AddYear Adds years to the current year

For more information go to http://msdn.microsoft.com/en-us/library/03ybds8y

Summary
Dates and time are easy to use in Visual Basic, and this tutorial gave you a starting point. There
are many ways you can format and manipulate the date. Date and time are a data type,
so remember if you are going to do some calculations based on the date and time it is best to
use DateTime.UtcNow.

Visual Basic Math


Computers are good with numbers, so it's obvious they can perform mathematical calculations
such as adding, subtracting, and square root, as well as cos, sin, tan, and hyp. At times,
problems need to be solved, for example 2 + 6 * 5. You might think the answer to this is 40 ( 2
+ 6 = 8 * 5 = 40 ), but in fact it is 32 (multiplication or division are always done first). You can
force 2 + 6 to be calculated first by putting brackets around it like this:

Console.WriteLine((2 + 6) * 5)
Console.ReadLine()
Now the answer you should get is 40.

Another example is when there is multiplication and division; which one is done first? You start
from the left to the right, for example:

Console.WriteLine(30 / 2 * 3)
Console.ReadLine()
The answer for this is 45. Since we had both division and multiplication it starts from the left.
Again, you can force 2 * 3 to be done first by putting brackets around it, and then the answer
would be 5.

Division
With division you can format the result, for example:

Dim Divide As Integer

Divide = 5

Console.WriteLine(9 / Divide)
Console.ReadLine()
It will output 1.8. We can force this to an integer value by using CType function. Then it would
look like this:
Dim Divide As Integer

Divide = 5

Console.WriteLine(CType(9 / Divide, Integer))


Console.ReadLine()
This time we use the CType function, and at the end specify the data type (integer). The result
is 2, as it is converted to the nearest whole number.

Shorthand Math
You can use a much simpler way to do arithmetic:

Dim Shorthand As Integer

Shorthand = 5

Shorthand += 8

Console.WriteLine(Shorthand)
Console.ReadLine()
In this case we assign the variable Shorthand the value 5 then add 8, but just move the
operator to the left of the equal sign. This works for addition, subtraction, and multiplication but
not division, since the result can be a decimal value.

Other Math Functions


You can also find square roots, power and round. To do this, at the top above Module
Module1 put Imports System.Math. Then write the following:
Console.WriteLine(Sqrt(8))
Console.ReadLine()
This finds the square root of 8, which is 2.828.......

Finding the power of 10 and 5:

Console.WriteLine(Pow(10, 5))
Console.ReadLine()
The answer is 100,000.

Rounding:

Console.WriteLine(Round(8.7))
Console.ReadLine()
This rounds to 9 (do not confuse this with Rnd, which is Random).
There are many more math functions that can be done with the .Net Framework. For more
information see the MSDN reference.
Summary
 Multiplication and division are always done first

 If there are both multiplication and division, start from left to right

 For shorthand math put the operator on the left of the = sign

 To use math functions such as sqrt, pow, round, make sure you import system.math

Visual Basic Operators


Equality Operators
Operator Description Example

= Is equal to x=y

if NOT x = y Then
NOT NOT equal to
End If

Relational Operators
Operator Description Example

< Less than if y < x ThenEnd If

> Greater Than if x > y ThenEnd If

<= Less than but equal to if x <= y ThenEnd If

>= Greater than but equal to if y >= x ThenEnd if

Conditional Operators
Operator Description Example

Compare two variables if a


AND If x AND y ThenEnd If
AND b equals
Compare two variables if a
OR If x or y ThenEnd If
OR b equals

Arithmetic Operators
Operator Description Example

+ Addition Operator 5+5

/ Division Operator 10 / 5

* Multiplication Operator 10 * 8

Other Operators
Operator Description Example

& Concatenation "a" & "b"

These are all very common operators and it is important to learn all of them.

Read more at: https://www.thecodingguys.net/tutorials/visualbasic/vb-operators

You might also like