Sie sind auf Seite 1von 17

Visual Basic .

Net
Primer programa en Visual Basic:
'Mi primer programa visual basic Module modSecondWelcome Sub Main() Console.Write("welcome to ") Console.WriteLine("visual basic") End Sub End Module

Cuando un programa corre es invocado el procedimiento Main, que es considerado el punto de inicio del programa. El mtodo Console.Write() muestra su parmetro en la ventana de comando de Windows y ubica el cursor al final de la lnea pero el mtodo Console.WriteLine() ubica cursor al inicio de la siguiente lnea.

Tipos de Datos Visual Basic


' Addition program. Module modAddition Sub Main() Dim firstNumber, secondNumber As String Dim number1, number2, sumOfNumbers As Integer Console.Write("Please enter the first integer: ") firstNumber = Console.ReadLine() Console.Write("Please enter the second integer: ") secondNumber = Console.ReadLine() number1 = firstNumber number2 = secondNumber sumOfNumbers = number1 + number2 Console.WriteLine("The sum is {0}", sumOfNumbers) End Sub End Module

El mtodo Console.ReadLine() lee el numero introducido por el usuario y lo almacena en la variable firstNumber y lo guarda como string La sentencia: number1 = firstNumber Convierte el string en un integer

Declaracin de variables:
Se pueden declarar varias declarar distintas variables en la misma instruccin sin necesidad de repetir el tipo de datos. En las instrucciones siguientes, las variables i, j y k se declaran como tipo Integer, l y m como Long, y x e yomo Single:

Dim i, j, k As Integer ' All three variables in the preceding statement are declared as Integer. Dim l, m As Long, x, y As Single ' In the preceding statement, l and m are Long, x and y are Single.

Los tipos bsicos de visual Basic son:


Tipo de Visual Basic Estructura de tipo Common Language Runtime Boolean Asignacin Intervalo de valores de almacenamien to nominal En funcin True o False de la plataforma de implementaci n 1 byte 2 bytes 0 a 255 (sin signo) 0 a 65535 (sin signo)

Boolean

Byte Char (carcter individual) Date

Byte Char

DateTime

8 bytes

0:00:00 (medianoche) del 1 de enero de 0001 a 11:59:59 p.m. del 31 de diciembre de 9999.

Decimal

Decimal

16 bytes

0 a +/79.228.162.514.264.337.593.543.95 0.335 (+/-7,9... E+28) sin separador decimal; 0 a +/7,9228162514264337593543950335 con 28 posiciones a la derecha del decimal; el nmero distinto de cero ms pequeo es +/0,0000000000000000000000000001 (+/-1E-28)

Double (punto flotante de precisin doble)

Double

8 bytes

-1,79769313486231570E+308 a 4,94065645841246544E-324 para los valores negativos; 4,94065645841246544E-324 a 1,79769313486231570E+308 para los valores positivos

Integer

Int32

4 bytes

-2.147.483.648 a 2.147.483.647 (con signo) -9.223.372.036.854.775.808 a 9.223.372.036.854.775.807 (9,2...E+18 ) (con signo) Cualquier tipo puede almacenarse en una variable de tipo Object

Long (entero largo)

Int64

8 bytes

Object

Object (clas 4 bytes en e) plataforma de 32 bits 8 bytes en plataforma de 64 bits

SByte Short (entero corto) Single (punto flotante de precisin simple)

SByte Int16

1 byte 2 bytes

-128 a 127 (con signo) -32.768 a 32.767 (con signo)

Single

4 bytes

-3,4028235E+38 a -1,401298E45 para los valores negativos; 1,401298E-45 a 3,4028235E+38 para los valores positivos

String (longitud variable)

String (clas En funcin 0 a 2.000 millones de caracteres e) de la Unicode aprox. plataforma de implementaci n UInt32 UInt64 4 bytes 8 bytes 0 a 4.294.967.295 (sin signo) 0 a 18.446.744.073.709.551.615 (1,8...E+19 ) (sin signo) Cada miembro de la estructura tiene un intervalo de valores determinado por su tipo de datos y es independiente de los intervalos de valores correspondientes a los dems miembros. 0 a 65.535 (sin signo)

UInteger ULong

UserDefined(estructu ra)

(hereda En funcin de ValueType de la ) plataforma de implementaci n

UShort

UInt16

2 bytes

El mtodo Console.WriteLine()
Console.WriteLine("The sum is {0}", sumOfNumbers)
Usamos {0} para imprimir un contenido de una variable que esta fuera, si consideramos que el contenido de la variable es 117, indica que el argumento despus del string(en este caso, sumOfNumbers) ser evaluado e incorporado dentro del string en el lugar del formato ,el string resultante ser the sum is 117,formatos adicionales ({0},{1},{2},etc) pueden ser insertados dentro del string. cada formato adicional requiere una correspondiente nombre de variable o valor. Por ejemplo, si el argumento para WriteLine() es:

"The values are {0}, {1} and {2}", number1, number2, 7


El valor de number1 reemplaza {0} (porque es la primera variable), el valor de numbe2 reemplaza {1} (porque es la segunda variable)y el valo7 reemplaza {2} (porque esta es la tercer variable).

Uso avanzado de MSGBOX ()


Imports System.Windows.Forms Module modSquareRoot Sub Main() Dim valorRetorno As Integer Dim root As Double = Math.Sqrt(2) valorRetorno = MsgBox("Square: " & root, VBYESNOCANCEL, "VentBlady") Console.WriteLine(valorRetorno) End Sub End Module

MSGBOX ("Mensaje", VBOKONLY, "Ttulo")

MSGBOX ("Mensaje", VBOKCANCEL, "Ttulo")

MSGBOX ("Mensaje", VBYESNOCANCEL, "Titulo")

MSGBOX ("Mensaje", VBABORTRETRYIGNORE, "Ttulo")

MSGBOX ("Mensaje", VBYESNO, "Ttulo")

MSGBOX ("Mensaje", VBRETRYCANCEL, "Ttulo")

MSGBOX ("Mensaje", VBCRITICAL, "Ttulo")

MSGBOX ("Mensaje", VBQUESTION, "Ttulo")

MSGBOX ("Mensaje", VBEXCLAMATION, "Titulo")

MSGBOX ("Mensaje", VBINFORMATION, "Ttulo")

Cuando el usuario pulse uno de los dos botones devolver uno de los diferentes valores: Botn Aceptar Cancelar Anular Reintentar Ignorar S No Valor 1 2 3 4 5 6 7

Control de Flujo
Module seleccion Sub Main() Dim notaAlum As Integer notaAlum = 40 If notaAlum >= 60 Then Console.WriteLine("paso") Else Console.WriteLine("fallo") End If End Sub End Module

Multiple Seleccin
Module seleccion Sub Main() Dim notaAlum As Integer notaAlum = 40 If grade >= 90 Then Console.WriteLine("A") ElseIf grade >= 80 Then Console.WriteLine("B") ElseIf grade >= 70 Then Console.WriteLine("C") ElseIf grade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If End Sub End Module

Bucle While :
Estructura de repeticin:

Module bucleWhile Sub Main() Dim product As Integer = 0 While product <= 10 Console.Write(product) product = product + 1 End While End Sub End Module

Bucle Do While Loop estructura de repeticin:


Module bucleWhile Sub Main() Dim product As Integer = 0 Do While product <= 10 Console.WriteLine(product) product = product + 1 Loop End Sub End Module

Bucle Do While Loop estructura de repeticin:


Module bucleWhile Sub Main() Dim counterVariable As Integer = 0 Do Console.WriteLine("counterVariable: {0}", counterVariable) counterVariable = counterVariable + 1 Loop While counterVariable < 10 End Sub End Module

Do Until/Loop

Module bucleDoWhile Sub Main() Dim product As Integer = 0 Do Until product > 10 Console.WriteLine(product) product = product + 1 Loop End Sub End Module

Operadores de asignacin:

Bucle for:
Module bucleWhile Sub Main() Dim counter As Integer For counter = 2 To 10 Step 2 Console.Write(counter & " ") Next End Sub End Module

Bucle for Each:


Module bucleWhile Sub Main() Dim friends() As String = {"A", "B", "C", "D", "E"} Dim friendName As String For Each friendName In friends Console.WriteLine(friendName) Next End Sub End Module

Imports System.Windows.Forms Module modInterest Sub Main() Dim amount, principal As Decimal Dim rate As Double Dim year As Integer Dim output As String principal = 1000.0 rate = 0.05 output = "Year" & vbTab & "Amount on deposit" & vbCrLf For year = 1 To 10 amount = principal * (1 + rate) ^ year output &= year & vbTab & String.Format("{0:C}", amount) & vbCrLf Next Console.Write(output) End Sub End Module

Imports System.Windows.Forms Module modInterest Sub Main() Dim amount, principal As Decimal Dim rate As Double Dim year As Integer Dim output As String principal = 1000.0 rate = 0.05 output = "Year" & vbTab & "Amount on deposit" & vbCrLf For year = 1 To 10 amount = principal * (1 + rate) ^ year output &= year & vbTab & String.Format("{0:C}", amount) & vbCrLf Next MsgBox(output, VBOKONLY, "Ventana Interes") End Sub End Module

Select Case Multiple-Selection Structure


Module bucleWhile Sub Main() Dim targetInteger As Integer = 13 Select Case targetInteger Case Is < 10 Console.WriteLine("Less than 10") Case 10 To 14 Console.WriteLine("10-14") Case 15 Console.WriteLine("15!") Case Else Console.WriteLine("Value not found") End Select End Sub End Module

Sub Rutinas
Los procedimientos de definen de la siguiente manera:

Module modSecondWelcome Sub Main() ' call Sub procedure PrintPay 4 times PrintPay(40, 10.5) PrintPay(38, 21.75) PrintPay(20, 13) PrintPay(50, 14) End Sub ' print dollar amount earned in command window Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal) ' pay = hours * wage Console.WriteLine("The payment is {0:C}", hours * wage) End Sub ' PrintPay End Module

Funciones
Las funciones se definen de la siguiente manera:

Module modSecondWelcome Sub Main() Dim i As Integer ' counter Console.WriteLine("Number" & vbTab & "Square" & vbCrLf) ' square numbers from 1 to 10 For i = 1 To 10 Console.WriteLine(i & vbTab & Square(i)) Next End Sub Function Square(ByVal y As Integer) As Integer Return y ^ 2 End Function ' Square End Module

Variables por valor y referencia


Module modSecondWelcome Sub DoubleItByVal(ByVal X As Single) X *= 2 End Sub Sub DoubleItByRef(ByRef X As Single) X *= 2 End Sub Sub Main() Dim value As Single value = 10 DoubleItByVal(value) Console.WriteLine(value) value = 10 DoubleItByRef(value) Console.WriteLine(value) End Sub End Module

Mdulos pre-empaquetados
' Assembly building example in the .NET Framework. Imports System Namespace myStringer Public Class Stringer Public Sub StringerMethod() Console.WriteLine("This is a line from StringerMethod.") End Sub End Class End Namespace

Use el comando siguiente para compilar este cdigo:

Vbc /t:module Stringer.vb

En el siguiente ejemplo se muestra el cdigo de Client.

Imports System Imports myStringer 'The namespace created inStringer.netmodule. Class MainClientApp ' Shared method Main is the entry point method. Public Shared Sub Main() Dim myStringInstance As New Stringer() Console.WriteLine("Client code executes") 'myStringComp.Stringer() myStringInstance.StringerMethod() End Sub End Class

Use el comando siguiente para compilar este cdigo:

vbc /addmodule:Stringer.netmodule /t:module Client.vb

Una compilacin crea dos archivos assembly:

vbc /out:Stringer.netmodule Stringer.vb /out:Client.exe Client.vb

Crear mltiples archivos assembly:

al Client.netmodule Stringer.netmodule /main:MainClientApp.Main /out:myAssembly.exe /target:exe

Compilar un programa en Visual Basic


Compilar un programa de visual basic en Windows solo tienes que abrir el cmd de la Shell y luego ubicarte en el directorio donde se encuentra el script de tu recurso y tapear una de los dos comandos siguientes:

vbc /target:exe miRecurso.vb vbc /target:winexe miRecurso.vb

La etiqueta /target:winexe es si se trata de una aplicacin Gui y /target:exe si es una aplicacin de consola. Para ello la se debe incluir en la variable de entorno la ruta del Framework con el que trabaja, por ejemplo:

C:\Windows\Microsoft.NET\Framework\v4.0.30319

Das könnte Ihnen auch gefallen