Visual Basic : Core 1

Download Report

Transcript Visual Basic : Core 1

Visual Basic : Core 1
•
•
•
•
Projects
Data types
Variables and constants
Comments, hex constants and line
continuation
• Forms and controls
• A calculator program
What's in a Project
• Project = code for an application
• Form = window – several in a project
• .frm has data eg form width height, and
event-driven subroutines
• Module = VB code (general)
• Class = defining your own classes
• Can make into .exe
Project files
VERSION 5.00
Begin VB.Form Form1
Caption
= "Form1"
ClientHeight = 2445
ClientLeft
= 5145
ClientTop
= 4110
ClientWidth = 5070
LinkTopic
= "Form1"
ScaleHeight = 2445
ScaleWidth
= 5070
Begin VB.CommandButton Command1
Caption
= "Command1"
Height
= 615
Left
= 1200
TabIndex
= 0
Top
= 600
Width
= 1815
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private Sub Command1_Click()
MsgBox ("Hello world")
End Sub
Inside a .frm file
Variables
•
•
•
•
Dim x as Integer
Dim x,y as Integer NO!
Is case sensitive (kind of)
Variable naming conventions
– Microsoft Simonyi Hungarian Reddick
– House rules
• Assignment statement –
x=4
• Option Explicit YES!
• Constants –
Private Const MyInt As Integer = 5
Comments, line continuation and hex
• Comments start with an apostrophe
• 'and run to the end of the line
• A very long statement can use a_
to continue onto the next line
• Hex constants written like &HFF0012
Data types
•
•
•
•
•
•
•
•
•
Integer Long
Single Double
Currency
Byte unsigned 0 - 255
String
Boolean
Date
Object
Variant - do not use except explicit reason
VarType to determine type
Dim x As Variant
x=1
MsgBox (VarType(x))
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
17
36
8192
Empty (uninitialized)
Null (no valid data)
Integer
Long integer
Single-precision floating-point number
Double-precision floating-point number
Currency value
Date value
String
Object
Error value
Boolean value
Variant (used only with arrays of variants)
A data access object
Decimal value
Byte value
Variants that contain user-defined types
Array
Data type conversion
DIM x as integer
x = Cint("10")
Conversion function
Converts an expression to
Cbool
Boolean
Cbyte
Byte
Ccur
Currency
Cdate
Date
CDbl
Double
Cint
Integer
CLng
Long
CSng
Single
CStr
String
Cvar
Variant
CVErr
Error
Form properties
Controls and properties
Example - calculator
Exercise – try this out.
Then add and program subtract,
multiply and divide buttons.
Ignore invalid numbers and divide
by zero – done later
Private Sub Command1_Click()
Dim num1 As Integer
Dim num2 As Integer
Dim result As Integer
num1 = Text1.Text
num2 = Text2.Text
result = num1 + num2
Label1.Caption = result
End Sub