01May10

Ken’s Visual Basic Notes Ken’s Visual Basic Notes

1

Contents
Variables......................................................................................................................................................... 2 Constants ........................................................................................................................................................ 2 DataTypes....................................................................................................................................................... 3 Arrays ............................................................................................................................................................. 4 Strings............................................................................................................................................................. 5 Format ........................................................................................................................................................ 5 Format Codes ......................................................................................................................................... 5 Date Time ................................................................................................................................................... 7 Operations ...................................................................................................................................................... 7 Logical Expressions........................................................................................................................................ 7 Decisions ........................................................................................................................................................ 8 Looping .......................................................................................................................................................... 9 Collections, Iteration .................................................................................................................................. 9 Subroutines, Functions ................................................................................................................................. 10 Error Handling .............................................................................................................................................. 11 Summary of Other Statements ...................................................................................................................... 12 Summary of Visual Basic Functions ............................................................................................................ 13 File I/O ......................................................................................................................................................... 15

When decleared within the Declarations section at the start of a module. Variable retains its value from one execution of the procedure to another dStartDate = #January 1.01May10 Ken’s Visual Basic Notes 2 Variables Dim | Private | Static varname [As type] Typical variable declarations Dim sErrorMessage As String Dim sUserName As String * 25 Dim iIndex As Integer. fInterestRate As Single Private bAddMode As Boolean Public iUserStatus As Integer Static iRunningValue As Integer Keyword Dim Scope Variable only available within the procedure or module that declares it. Variable is available to the procures in all the modules of a project. it’s known as a module-level variable. (g) Static Variable only available within the procedure or module that declares it. 2008# ‘ use # delimiters for dates Constants [ Private | Public ] As Const constname [As type ] = expression Typical declarations for user defined contants Private Const iMonths As Integer = 60 Public Const gfInterestrate As Single = . Variable is only available to the procedures within the module that declares it. Private Can only be coded in the declarations section of a module. (m) Public Can only be coded in the declarations section of a module.125 / 2 .

767 long integer float Dim aString As String * 20 86.0# 86& 86.g.00@ #12-Jan-1999# #2:56 PM# 86.768 to 32.92) str = CStr(4.0! Boolean Byte Currency Date Double Integer Long Object Single String Variant bln or b byt or t cur or c dtm or d dbl or p int or i lng or l obj or o sng or f str or s vnt or v IsEmpty(anArg) IsNull(anArg) IsNumeric(aString) VarType(anArg) VarType(aString) returns True if has not been initialized since declaring returns True for (e.92) ‘returns 4 Hex(11) ‘returns B ascii number of first char in string rounds to next highest int truncate fraction rounds down .92) ‘returns 4 int = Int(4.92) int = Fix(4.) empty string return True if can be converted to numeric type returns what this argument can be converted into 0=vbEmpty 1=vbNull 2=vbInteger 3=vbLong 4=vbSingle 5=vbDouble 6=vbCurrency 7=vbDate 8=vbString 9=vbObject 10=vbError 11=vbBoolean 12=vbVariant 13=vbDataObject (DAO database access) 14=vbDecimal 17=vbByte 8192+int=vbArray array argument of the type specified by the int addition to 8192 int = Asc(str) int = CInt(4.01May10 Ken’s Visual Basic Notes 3 DataTypes Datatype Prefix Suffix Literal (to force the literal to be a data type) True (or +1 or –1) or False (or 0) 0 to 255 must embed literal date & time values inside # signs float (double precision) -32.

01May10 Ken’s Visual Basic Notes 4 Oct(8) ‘ returns 10 Str(10) ‘ returns string 10 Val(“10”) ‘ returns 10 string to integer Arrays Arrays start indexing at 0 Strings and Collections start indexing at 1 Dim iValues (9) As Integer Dim iValues (1 To 10) As Integer Dim iValues (4.0) = 0.4) As Single cRate(0. 1 To 5) As Integer ‘ index values are 0-9 ‘ index values are 1-10 ‘ two dimensional array ‘ another two dimensional array Dim cRate (1 To 10) As Single cRate(1) = 0.01 Dim cRate (1.01 . 4) As Integer Dim iValues (1 To 5.

M.678.00. and adds the percent sign to the right of the number display the time in 24 hour format “General Number” Medium Time” “On/Off” “Percent” “Scientific” “Short Time” “True/False” “Yes/No” Format Codes txtAmount = Format (curAmount * interestRate. “$#####. “Currency”) displays at least one digit before and two digits following the decimal point.000”) ‘displays to 3 places txtAmount = Format (curAmount * interestRate. “$#####”) ‘displays no decimal places longTime = Format (“17:08:06”.] bigstr1. beginning at start if specified default delimiter is a space case length (works on numbers too) careful – there’s both a Mid function and Mid statement . start. the # would show nothing if the result were zero txtAmount = Format (curAmount * interestRate. multiplied by 100.##0.delimiter]) aString = LCase(str) aString = UCase(str) size = Len(str) aSubString = Mid(str.01May10 Ken’s Visual Basic Notes 5 Strings Arrays start indexing at 0 Strings and Collections start indexing at 1 & (or +) concatenate Str(10) ‘ returns string 10 Val(“10”) ‘ returns 10 integer to string string to integer Format aVariant = Format(expression. “$###.00”) ‘ if the value happens to be $0. intStart [intLen]) ‘12345 returns porition of littlestr2 within bigstr1. strFormat) strFormat “Currency” “Fixed” Format(1234. with no thousandths separator displays the number with no thousandths separator displays the time in 12 hour format display “On” if the value contains a nonzero value displays the number. whereas if you used a # in place of each 0. littlestr2 [. “Long Time”) ‘ returns: 5:08:06 P. littlestr2) aSubString = InStrRev(bigstr1. the zeros ensure that the value prints. aChar = Chr(int) aSubString = InStr([start.]) aString = Join (aStringList [.

0-255 for non double byte character systens -32768-32767 for double byte character systems Finds the starting position of one string within another comparemode: 0 vbBinaryCompare 1 vbTextCompare 2 vbDatabaseCompare (Access only) . int) aString = Str (int) anInt = Val(str) aString = Trim(str) aString = RTrim(str) aString = LTrim(str) InStr Mid statement replaces part of a string with another value abbre = True for abbreviated month returns int far right characters removes blanks at the ends Returns the occurrence of one string within another Binary data conversion functions Asc(string) AscB(string) ‘ for the first byte AscW(string) ‘ for unicode Instr ( [start. int) aString = Left(str. 4) = “rode” ‘I rode home aString = Month(month [.abbre]) aString = Right (str. 3. _ comparemode]) InStrB ‘use to compare byte (as opposed to character) data within a string MidB LeftB RightB ChrB Returns an integer that represents the character code of the first character of the string.] stringtosearch. stringtofind[.01May10 Ken’s Visual Basic Notes 6 strSentence = “I flew home” Mid(strSentence.abbre]) aString = WeekdayName (weekday [.

18) ‘July 18. dteUserDate) ‘returns 20 days beyond dteUserDate strIntrv: “h”=hour. 25) ‘2:32:35 P. 7. 18-31) ’returns 31 days prior to July 18. yyyy=year DateDiff(strIntrv1.add. intDay) dte = DateSerial(1998. dte1. 1998 dte = DateSerial(1998. 1998 DateAdd(strIntrv1.M. aDte = TimeSerial(14-20. 7. q=quarter. w=weekday. d=day. dte2) Now Time Timer lngBefore = Timer … lngAfter = Timer lngTimeDiff = lngAfter – lngBefore ‘diff in seconds TimeSerial(hour. 32. s=second. 20.div.sub first. min. dteDate) DateAdd(“d”. 25) ’20 hours before 2:32:35 P. dte2) no_of_weeks = DateDiff(“ww”. ww=week. intMonth. y=day of year.01May10 Ken’s Visual Basic Notes 7 Date Time isDate(aDate) ‘ is it a valid date? Date intYear = Year(Date) ‘ returns current year DateSerial(intYear. 32. sec) dteTimePaid = TimeSerial(14. returns current date returns the date corresponding to ints passed in adds the intN value to the date specified by dteDate for the given strIntrv1 returns the number of time intervals (specified by strIntrv) between the two dates returns the current date-time in the date format returns the current time returns the number of seconds since midnight return the date and time in the internal date format for the time specified Operations aRoot = aFloat ^ (1/5) ‘ raise to a power Order: mult. n=minutes. m=month. then left to right evaluation Logical Expressions if theAnswer = “yes” . dte1.M. intN.

NET. Or.01May10 Ken’s Visual Basic Notes 8 Relational Operators: =. >. >=. And. <>. Imp The two very rarely used VB 6 operators Imp and Eqv have disappeared in VB. but two new operators. AndAlso and OrElse have been added Decisions If (aNumber = anotherNumber) Then ‘ not = = If aNumber < > anotherNumber Then ‘ not ! = If Not (aNumber < > anotherNumber ) Then ‘ not ~ “Apple” <= “Orange” ‘ true If some_comparison Then Else End If If some_comparison Then ElseIf another_comparison Then End If If (A > B) And (C < D) Then If (A > B) Or (C < D) Then If Not (StrAns = “Yes”) Then Select Case iIndex Case 0. Xor.2 … Case 1 … Case 10 To 24 … Case Is >= 25 … Case Else … End Select . <=. Eqv. < Logical operations: Not.

Add “Ken” aList.Remove 3 ‘ removes the third item For Each aControl In Controls aControl. Iteration Public aList As New Collection aList.Visible = True Next aControl .01May10 Ken’s Visual Basic Notes 9 Looping Do While ( ) … Loop Do Until ( ) … Loop Do … Loop Until ( ) For i = startVal To endVal Step 1 ‘ Step 1 is optional … Next i Collections.Count aList.Add “Sally” int = aList.

anInteger) ‘ calling w fully qualified name Sub foo (parm1 As String. ‘ default is to pass as a ref x as Int. ByVal Y as Int ) ‘ pass by value Dim maxX As Int Dim maxY As Int x = x + 1 ‘ changes x in the callers space y = y + 1 ‘ does NOT change in the callers space … End Sub aSub(string1. Functions Public Sub aSub(aString As String. aSub(string1.01May10 Ken’s Visual Basic Notes 10 Subroutines. Optional parm2 As Integer = 1) ‘ optional parm … End Sub Private Sub cmdCompute_Click () … End Sub ‘ subroutines do not return a value Public Function ErrorCheck() As Integer … ErrorCheck = 1 ‘ set return value Exit Function … End Function ‘ functions return a value . anInteger) ‘ calling a private subroutine w parms passed by reference Module3.

Number & vbCrLf _ & “ Error Description: “ & Err.01May10 Ken’s Visual Basic Notes 11 Error Handling Syntax On Error GoTo label On Error Resume Next On Error Goto ( ) Resume Resume Next Exit Sub Meaning On error goto the line following the label Resume processing on the next statement after the one that caused the error Disable the error handling code Use this in an error handling routine to resume processing with the statement that caused the error Use this in an error handling routine to resume processing after the statement that caused the error Return to the caller Private Sub somesub_Click ( ) On Error GoTo ErrorHandler … Exit Sub ErrorHandler: MsgBox “Error Number: “ & Err.Description End Sub .

Exit For. or Exit Function Miscellaneous statements Type Often used to define the fields within the records of a structure .01May10 Ken’s Visual Basic Notes 12 Summary of Other Statements Statements for working with forms Load Unload Statements for working with string variables Lset Mid Rset Left align a string within a string variable Replaces a specified number of characters in a string variable with characters from another string Right aligns a string within a string variable Load a form into memory Unloads a form Statements for controlling program execution End Stop Exit Terminates a program immediately and releases all resources Sets a breakpoint in the code that suspends execution Provides a way to prematurely exit from a Do loop. Exit Sub. Sub procedure or function when used within these forms: Exit Do. For loop.

_ vbYesNo + vbDefaultButton. waits for the user to click a button and returns an integer indicating which button the user clicked If MsgBox(“Want to Exit?”.01May10 Ken’s Visual Basic Notes 13 Summary of Visual Basic Functions Some of the date and time functions Date Now Time DateValue Returns the current date Returns the current date and time Returns the current time Receives a date string and returns a date numeric value Some of the math functions Int Val Rnd Returns the integer portion of a number Returns the number contained in the string as an numeric value Returns the next random number as a decimal franction between 0 and 1 The immediate If function IIf Evaluates a conditional expression and returns ome value if the epxression is True and another value if the expression is False Two dialog functions MsgBox Displays a message in a dialog box. if msgText = “” Then Exit Sub . “InputBoxDemo”). “Confirm Exit”) = vbNo Then … InputBox Returns a string that contains what the user entered msgText = InputBox(“Enter some words”_ .

ShowDialog() To display a form as a Modal dialogue box. Me. the form is displayed as a Modeless form.01May10 Ken’s Visual Basic Notes 14 Forms Dim frmDialogue As New frmSecond frmDialogue. you use the ShowDialog method. If you use the Show method.Hide() .

StreamReader(fullFileName) While (aLine <> Nothing) aLine = Trim(fileReader.01May10 Ken’s Visual Basic Notes 15 File I/O Open “d:\data\myfile. Do Until (Eof(#1) = True) Input #1. “some line to write” Write #1.dat” For Input As #2 Open “d:\data\myfile. “end w semicolon to not insert newlinee”. aStringLine ‘ read a whole line Loop Type Record ‘ user defined type ID As Integer Name As String * 20 End Type Dim aRecord As Record ‘declare variable Do Until (Eof(#1) = True) Input #1.dat” For Append As #1 Open “d:\data\myfile.IO. End While .dat” For Output As #3 int_next_available_file_no = FreeFile() Write #1.. aRecord ‘ reads the record Loop Visual Basic 2008 Has 3 main pairs of readers and writers: BinaryReader and BinaryWriter StreamReader and StreamWriter (to process line-based text files) StringReader and StringWriter (uses a standard string instead of a file) TextReader and TextWriter (provides a base class for non-binary readers..ReadLine()) . parm3 Loop ‘read comma separated parms Do Until (Eof(#1) = True) Line Input #1. parm1. parm2. writers) Dim aLine As String = "" Dim fileReader As New System.

but limited features ADO = ActiveX Data Objects ADO-> OLE DB -> Data source Preferred way to access DB with VB6 and above ADO Object Model Connection Dim cnAP As Connection Set cnAP = New Connection Recordset Dim rsVendors As Recordset Set rsVendors = New Recordset rsVendors. Jet can reduce program efficiency RDO = Remote Data Objects Introduced in VB5.Open “Vendors”. adLockOptimistic. cnAP.01May10 Ken’s Visual Basic Notes 16 Microsoft Database Technologies DAO = Data Access Options Uses Jet Database Engine (which then passes requests to ODBC). Not as advanced as SQL Server and Oracle. adCmdTable Fields Field Command Parameters Parameter Errors Error . originally designed for use with Access DB. passes requests directly to ODBC. adOpenKeyset.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times