The data type of the return value is the same as that of the number argument. However, if the number argument is a Variant of VarType (String) and can be converted to a number, the return value will be a Variant of VarType (Double). If the numeric expression results in a Null, _Abs returns a Null.
Sub Main
Dim Msg, X, Y
X = InputBox("Enter a Number:")
Y = Abs(X)
Msg = "The number you entered is " & X
Msg = Msg + ". The Absolute value of " & X & " is " & Y
MsgBox Msg 'Display Message.'
End Sub
The parameter app is a string expression and is the name that appears in the title bar of the application window to activate.
Sub Main ()
AppActivate "Microsoft Word"
SendKeys ``%F,%N,Cypress Enable'',True
Msg = ``Click OK to close Word''
MsgBox Msg
AppActivate ``Microsoft Word'' ` Focus back to Word
SendKeys ``%F,%C,N'', True `Close Word
End Sub
Sub Main ()
Dim I, Msg ' Declare variables.
For I = Asc("A") To Asc("Z") ' From A through Z.
Msg = Msg & Chr(I) ' Create a string.
Next I
MsgBox Msg ' Display results.
End Sub
The argument rad can be any numeric expression. The result is expressed in radians
Sub AtnExample ()
Dim Msg, Pi ' Declare variables.
Pi = 4 * Atn(1) ' Calculate Pi.
Msg = "Pi is equal to " & Str(Pi)
MsgBox Msg ' Display results.
End Sub
Sub BeepExample ()
Dim Answer, Msg ' Declare variables.
Do
Answer = InputBox("Enter a value from 1 to 3.")
If Answer >= 1 And Answer <= 3 Then ' Check range.
Exit Do ' Exit Do...Loop.
Else
Beep ' Beep if not in range.
End If
Loop
MsgBox "You entered a value in the proper range."
End Sub
You are never required to use the Call statement when calling an Enable subroutine or a DLL function. Parentheses must be used in the argument list if the Call statement is being used.
Sub Main ()
Call Beep
MsgBox "Returns a Beep"
End Sub
Sub Main ()
Dim y As Integer
y = 25
If VarType(y) = 2 Then
Print y
x = CDbl(y) 'Converts the integer value of y to a double value in x
Print x
End If
End Sub
Syntax: [drive:] [ \ ] dir[\dir]...
The parameter pathname is a string limited to fewer then 128 characters. The drive parameter is optional. The dir parameter is a directory name. ChDir changes the default directory on the current drive, if the drive is omitted.
Sub Main ()
Dim Answer, Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
CurPath = CurDir() ' Get current path.
ChDir "\"
Msg = "The current directory has been changed to "
Msg = Msg & CurDir() & NL & NL & "Press OK to change back "
Msg = Msg & "to your previous default directory."
Answer = MsgBox(Msg) ' Get user response.
ChDir CurPath ' Change back to user default.
Msg = "Directory changed back to " & CurPath & "."
MsgBox Msg ' Display results.
End Sub
Sub Main ()
Dim Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
CurPath = CurDir() ' Get current path.
ChDir "\"
ChDrive "G:"
Msg = "The current directory has been changed to "
Msg = Msg & CurDir() & NL & NL & "Press OK to change back "
Msg = Msg & "to your previous default directory."
MsgBox Msg ' Get user response.
ChDir CurPath ' Change back to user default.
Msg = "Directory changed back to " & CurPath & "."
MsgBox Msg ' Display results.
End Sub
Sub Main ()
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
TEXT 10, 10, 28, 12, "Name:"
TEXTBOX 42, 10, 108, 12, .nameStr
TEXTBOX 42, 24, 108, 12, .descStr
CHECKBOX 42, 38, 48, 12, "&CHECKME", .checkInt
OKBUTTON 42, 54, 40, 12
End Dialog
Dim Dlg1 As DialogName1
Dialog Dlg1
MsgBox Dlg1.nameStr
MsgBox Dlg1.descStr
MsgBox Dlg1.checkInt
End Sub
Sub ChrExample ()
Dim X, Y, Msg, NL
NL = Chr(10)
For X = 1 to 2
For Y = Asc("A") To Asc("Z")
Msg = Msg & Chr(Y)
Next Y
Msg = Msg & NL
Next X
MsgBox Msg
End Sub
Sub Main ()
Dim y As Long
y = 25
If VarType(y) = 2 Then
Print y
x = CInt(y) 'Converts the long value of y to an integer value in x
Print x
End If
End Sub
Sub Main ()
Dim y As Integer
y = 25
If VarType(y) = 2 Then
Print y
x = CLng(y) 'Converts the integer value of y to a long value in x
Print x
End If
End Sub
Sub Make3Files ()
Dim I, FNum, FName ' Declare variables.
For I = 1 To 3
FNum = FreeFile ' Determine next file number.
FName = "TEST" & FNum
Open FName For Output As FNum ' Open file.
Print #I, "This is test #" & I ' Write string to file.
Print #I, "Here is another "; "line"; I
Next I
Close ' Close all files.
End Sub
A constant must be defined before it is used.
The definition of a Const in Cypress Enable outside the procedure or at the module level is a global. The syntax Global Const and Const are used below outside the module level are identical.
A type declaration character may be used however if none is used Enable will automatically assign one of the following data types to the constant, long (if it is a long or integer), Double (if a decimal place is present), or a String ( if it is a string).
Global Const GloConst = 142 '
Const MyConst = 122 'Global to all procedures in a module
Sub Main ()
Dim Answer, Msg, NL ' Declare variables.
Const PI = 3.14159
NL = Chr(10) ' Define newline.
CurPath = CurDir() ' Get current path.
ChDir "\"
Msg = "The current directory has been changed to "
Msg = Msg & CurDir() & NL & NL & "Press OK to change back "
Msg = Msg & "to your previous default directory."
Answer = MsgBox(Msg) ' Get user response.
ChDir CurPath ' Change back to user default.
Msg = "Directory changed back to " & CurPath & "."
MsgBox Msg ' Display results.
myvar =myConst + PI + GloConst
Print MyVar
End Sub
The argument rad must be expressed in radians and must be a valid numeric expression. Cos will by default return a double unless a single or integer is specified as the return value.
Sub Main()
Dim J As Double
Dim I As Single ' Declare variables.
Dim K As Integer
For I =1 To 10 '
Msg = Msg & Cos(I) & ", " 'Cos function call
J=Cos(I)
Print J
K=Cos(I)
Print K
Next I
MsgBox Msg ' Display results.
MsgBox Msg1
End Sub
Sub Command1_Click ()
Dim word6 As object
Set word6 = CreateObject("Word.Basic")
word6.FileNewDefault
word6.InsertPara
word6.Insert "Attn:"
word6.InsertPara
word6.InsertPara
word6.InsertPara
word6.Insert " Vender Name: "
word6.Bold 1
name = "Some Body"
word6.Insert name
word6.Bold 0
word6.InsertPara
word6.Insert " Vender Address:"
word6.InsertPara
word6.Insert " Vender Product:"
word6.InsertPara
word6.InsertPara
word6.Insert "Dear Vender:"
word6.InsertPara
word6.InsertPara
word6.Insert "The letter you are reading was created with Cypress Enable."
word6.InsertPara
word6.InsertPara
word6.Insert " Product Name: Cypress Enable"
word6.InsertPara
word6.Insert " Company Name: Cypress Software Inc."
word6.InsertPara
word6.InsertPara
MsgBox "You have just called Word 6.0 using OLE"
End Sub
Sub Main ()
Dim y As Integer
y = 25
If VarType(y) = 2 Then
Print y
x = CSng(y) 'Converts the integer value of y to a single value in x
Print x
End If
End Sub
CurDir returns a Variant; CurDir$ returns a String.
'Declare Function CurDir Lib "NewFuns.dll" () As String
Sub Form_Click ()
Dim Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
Msg = "The current directory is: "
Msg = Msg & NL & CurDir()
MsgBox Msg ' Display message.
End Sub
Date returns a Variant of VarType 8 (String) containing a date.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
x = Date()
Print Date
Print x
Print VarType(Date)
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
SysDate = Date
MsgBox Sysdate,0,"System Date"
MsgBox Now,0,"Now"
MsgBox MyTime,0,"MyTime"
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
The procedurename parameter is the name of the function or subroutine being called.
The Libname parameter is the name of the DLL that contains the procedure.
The optional Alias aliasname clause is used to supply the procedure name in the DLL if different from the name specified on the procedure parameter. When the optional argument list needs to be passed the format is as follows:
([ByVal] variable [As type] [,ByVal] variable [As type] ]])
The optional ByVal parameter specifies that the variable is [passed by value instead of by reference (see ``ByRef and ByVal'' in this manual). The optional As type parameter is used to specify the data type. Valid types are String, Integer, Double, Long, and Varaint (see ``Variable Types'' in this manual).
If a procedure has no arguments, use double parentheses () only to assure that no arguments are passed. For example:
Declare Sub OntTime Lib ``Check'' ()
Cypress Enable extensions to the declare statement. The following syntax is not supported by Microsoft Visual Basic.
Declare Function procedurename App [Alias aliasname$] [(argument list)][As Type]
This form of the Declare statement makes a reference to a function located in the executable file located in the application where Enable is embedded.
Declare Function GetFocus Lib "User" () As Integer
Sub Main
Dim hWindow%
Dim str1 As String *51
Dim str2 As String * 25
hWindow% = GetFocus()
End Sub
The Dialog() function is used to display the dialog box specified by DialogRecord . Dialogrecord is the name of the dialog and must be defined in a proceeding Dim statement.
> 0 A command button where 1 is the first PushButton in the definition of the dialog and 2 is the second, and so on.
' This sample shows all of the dialog controls on one dialog and how to
' vary the response based on which PushButton was pressed.
Sub Main ()
Dim MyList$(2)
MyList(0) = "Banana"
MyList(1) = "Orange"
MyList(2) = "Apple"
Begin Dialog DialogName1 60, 60, 240, 184, "Test Dialog"
Text 10, 10, 28, 12, "Name:"
TextBox 40, 10,50, 12, .joe
ListBox 102, 10, 108, 16, MyList$(), .MyList1
ComboBox 42, 30, 108, 42, MyList$(), .Combo1
DropListBox 42, 76, 108, 36, MyList$(), .DropList1$
OptionGroup .grp1
OptionButton 42, 100, 48, 12, "Option&1"
OptionButton 42, 110, 48, 12, "Option&2"
OptionGroup .grp2
OptionButton 42, 136, 48, 12, "Option&3"
OptionButton 42, 146, 48, 12, "Option&4"
GroupBox 132, 125, 70, 36, "Group"
CheckBox 142, 100, 48, 12, "Check&A", .Check1
CheckBox 142, 110, 48, 12, "Check&B", .Check2
CheckBox 142, 136, 48, 12, "Check&C", .Check3
CheckBox 142, 146, 48, 12, "Check&D", .Check4
CancelButton 42, 168, 40, 12
OKButton 90, 168, 40, 12
PushButton 140, 168, 40, 12, "&Push Me 1"
PushButton 190, 168, 40, 12, "Push &Me 2"
End Dialog
Dim Dlg1 As DialogName1
Dlg1.joe = "Def String"
Dlg1.MyList1 = 1
Dlg1.Combo1 = "Kiwi"
Dlg1.DropList1 = 2
Dlg1.grp2 = 1
' Dialog returns -1 for OK, 0 for Cancel, button # for PushButtons
button = Dialog( Dlg1 )
' MsgBox "button: " & button 'uncomment for button return vale
If button = 0 Then Return
MsgBox "TextBox: "& Dlg1.joe
MsgBox "ListBox: " & Dlg1.MyList1
MsgBox Dlg1.Combo1
MsgBox Dlg1.DropList1
MsgBox "grp1: " & Dlg1.grp1
MsgBox "grp2: " & Dlg1.grp2
Begin Dialog DialogName2 60, 60, 160, 60, "Test Dialog 2"
Text 10, 10, 28, 12, "Name:"
TextBox 42, 10, 108, 12, .fred
OkButton 42, 44, 40, 12
End Dialog
If button = 2 Then
Dim Dlg2 As DialogName2
Dialog Dlg2
MsgBox Dlg2.fred
ElseIf button = 1 Then
Dialog Dlg1
MsgBox Dlg1.Combo1
End If
End Sub
The types currently supported are integer, long, single, double and String
Sub Main
Dim x As Long
Dim y As Integer
Dim z As single
Dim a As double
Dim s As String
Dim v As Variant ' This is the same as Dim x or Dim x as any
The parameter ControlName is the name of the control on the dialog box. The parameter Value is the value to set it to. 1 = Enable, 0 = Disable. On is equal to 1 in the example below. If the second parameter is omitted the status of the control toggles. The entire example below can be found in the dialog section of this manual and in the example .bas files that ship with Cypress Enable.
Function Enable( ControlID$, Action%, SuppValue%)
Begin Dialog UserDialog2 160,160, 260, 188, "3", .Enable
Text 8,10,73,13, "New dialog Label:"
TextBox 8, 26, 160, 18, .FText
CheckBox 8, 56, 203, 16, "New CheckBox",. ch1
CheckBox 18,100,189,16, "Additional CheckBox", .ch2
PushButton 18, 118, 159, 16, "Push Button", .but1
OKButton 177, 8, 58, 21
CancelButton 177, 32, 58, 21
End Dialog
Dim Dlg2 As UserDialog2
Dlg2.FText = "Your default string goes here"
Select Case Action%
Case 1
DlgEnable "Group", 0
DlgVisible "Chk2", 0
DlgVisible "History", 0
Case 2
If ControlID$ = "Chk1" Then
DlgEnable "Group", On
DlgVisible "Chk2"
DlgVisible "History"
End If
If ControlID$ = "Chk2" Then
DlgText "History", "Push to display nested dialog"
End If
If ControlID$ = "History" Then
Enable =1
Number = 4
MsgBox SQR(Number) & " The sqr of 4 is 2"
x = Dialog( Dlg2 )
End If
If ControlID$ = "but1" Then
End If
Case Else
End Select
Enable =1
End Function
The parameter ControlName is the name of the control on the dialog box. The parameter String is the value to set it to.
If ControlID$ = "Chk2" Then
DlgText "History", "Push to display nested dialog"
End If
The parameter ControlName is the name of the control on the dialog box. The parameter Value is the value to set it to. 1 = Visible, 0 = Hidden. On is equal to 1. If the second parameter is omitted the status of the control toggles. The entire example below can be found in the dialog section of this manual and in the example .bas files that ship with Cypress Enable.
If ControlID$ = "Chk1" Then
DlgEnable "Group", On
DlgVisible "Chk2"
DlgVisible "History"
End If
[statements]
[Exit Do]
[statements]
Loop
Do
[statements]
[Exit Do]
[statements]
Repeats a group of statements while a condition is true or until a condition is met.
Sub Main ()
Dim Value, Msg ' Declare variables.
Do
Value = InputBox("Enter a value from 5 to 10.")
If Value >= 5 And Value <= 10 Then
Exit Do ' Exit Do...Loop.
Else
Beep ' Beep if not in range.
End If
Loop
End Sub
Sub Main()
Dim Var1 as String
Var1 = "hello"
MsgBox " Calling Test"
Test Var1
MsgBox Var1
End Sub
Sub Test(wvar1 as string)
wvar1 = "goodbye"
MsgBox "Use of End Statement"
End
End Sub
' Input Function Example'This example uses the Input function to read 10 characters at a time
from 'a file and display them in a MsgBox. This example assumes
that TESTFILE 'is a 'text file with a few lines of 'sample data.
Sub Main
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
MyStr = Input(10, #1) ' Get ten characters.
MsgBox MyStr
Loop
Close #1 ' Close file.
End Sub
' This example demonstrates some of the features of arrays. The lower bound
' for an array is 0 unless it is specified or option base has set it as is
' done in this example.
Option Base 1
Sub Main
Dim a(10) As Double
MsgBox "LBound: " & LBound(a) & " UBound: " & UBound(a)
Dim i As Integer
For i = 0 to 3
a(i) = 2 + i * 3.1
Next i
Erase( a ) ' If this line is uncommented then the values will all be 0
Print a(0),a(1),a(2), a(3)
End Sub
' This sample shows Do Loop with Exit Do to get out.
Sub Main ()
Dim Value, Msg ' Declare variables.
Do
Value = InputBox("Enter a value from 5 to 10.")
If Value >= 5 And Value <= 10 Then ' Check range.
Exit Do ' Exit Do...Loop.
Else
Beep ' Beep if not in range.
End If
Loop
End Sub
The value of the constant e is approximately 2.71828.
Sub ExpExample ()
'Exp(x) is e ^x so Exp(1) is e ^1 or e.
Dim Msg, ValueOfE ' Declare variables.
ValueOfE = Exp(1) ' Calculate value of e.
Msg = "The value of e is " & ValueOfE
MsgBox Msg ' Display message.
End Sub
The sourcefile and destinationfile parameters must be valid string expressions. sourcefile is the file name of the file to copy, destinationfile is the file name to be copied to.
[statements]
[Exit For]
[statements]
Repeats the group of statements for each element in an array of a collection. For each Ö Next statements can be nested if each loop element is unique. The For Each Next statement cannot be used with and array of user defined types.
Sub Main
dim z(1 to 4) as double
z(1) = 1.11
z(2) = 2.22
z(3) = 3.33
For Each v In z
Print v
Next v
End Sub
[statements]
Repeats the execution of a block of statements for a specified number of times.
Sub main ()
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping" ,z,y,x
Next z
Next y
Next x
End Sub
expression Expression to be formatted.
fmt A string of characters that specify how the expression is to displayed, or the name of a commonly-used format that has been predefined in Enable Basic. Do not mix different type format expressions in a single fmt parameter.
If the fmt parameter is omitted or is zero-length and the expression parameter is a numeric, Format[$] provides the same functionality as the Str[$] function by converting the numeric value to the appropriate return data type. Positive numbers convert to strings using Format[$] and lack the leading space reserved for displaying the sign of the value, whereas those converted using Str[$] retain the leading space.
To format numbers, you can use the commonly-used formats that have been predefined in Enable Basic or you can create user-defined formats with standard characters that have special meaning when used in a format expression.
Predefined numeric format names:
General Number Display the number as is, with no thousand Separators
Fixed Display at least one digit to the left and two digits to the right of the decimal separator.
Standard Display numbers with thousand separator, if appropriate; display two digits to the right of the decimal separator.
Percent Display number multiplied by 100 with a percent sign (%) appended to the right' display two digits to the right of the decimal separator.
Scientific Use standard scientific notation.
True/False Display False if number is 0, otherwise display True.
The following shows the characters you can use to create user-defined number formats.
Null string Display the number with no formatting.
If the number being formatted has fewer digits than there are zeros (on either side of the decimal) in the format expression, leading or trailing zeros are displayed. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, the number is rounded to as many decimal places as there are zeros. If the number has more digits to left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, the extra digits are displayed without modification.
Displays a digit or nothing. If there is a digit in the expression being formatted in the position where the # appears in the format string, displays it; otherwise, nothing is displayed.
The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator.
The percent character (%) is inserted in the position where it appears in the format string. The expression is multiplied by 100.
The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator.
This separator as specified in the format statement contains a comma surrounded by digit placeholders (0 or #). Two adjacent commas or a comma immediately to the left of the decimal separator (whether or not a decimal is specified) means ``scale the number by dividing it by 1000, rounding as needed.''
If the format expression contains at least one digit placeholder (0 or #) to the right of E-,E+,e- or e+, the number is displayed in scientific formatted E or e inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a plus sign next to positive exponents.
The actual character used as the time separator depends on the Time Format specified in the International section of the Control Panel.
The actual character used as the date separator in the formatted out depends on Date Format specified in the International section of the Control Panel.
- + $ ( ) Display a literal character.
space To display a character other than one of those listed, precede it with a backslash (\).
\ Display the next character in the format string.
The backslash itself isn't displayed. To display a backslash, use two backslashes (\\).
Examples of characters that can't be displayed as literal characters are the date- and time- formatting characters (a,c,d,h,m,n,p,q,s,t,w,y, and /:), the numeric -formatting characters(#,0,%,E,e,comma, and period), and the string- formatting characters (@,&,<,>, and !).
``String'' Display the string inside the double quotation marks.
To include a string in fmt from within Enable, you must use the ANSI code for a double quotation mark Chr(34) to enclose the text.
* Display the next character as the fill character.
Any empty space in a field is filled with the character following the asterisk.
Unless the fmt argument contains one of the predefined formats, a format expression for numbers can have from one to four sections separated by semicolons.
One section The format expression applies to all values.
Two The first section applies to positive values, the second to negative sections values.
Three The first section applies to positive values, the second to negative sections values, and the third to zeros.
Four The first section applies to positive values, the second to negative section values, the third to zeros, and the fourth to Null values.
The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.
If you include semicolons with nothing between them. the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays ``Zero'' if the value is zero.
Some sample format expressions for numbers are shown below. (These examples all assume the Country is set to United States in the International section of the Control Panel.) The first column contains the format strings. The other columns contain the output the results if the formatted data has the value given in the column headings
Format (fmt) Positive 3 Negative 3 Decimal .3 Null
#,##0.00;;;Nil 3.00 -3.00 0.30 Nil
$#,##0.00;($#,##0.00 ) $3.00 ($3.00) $0.30
0.00E+00 3.00E+00 -3.00E+00 3.00E-01
0.00E-00 3.00E00 -3.00E00 3.00E-01
Numbers can also be used to represent date and time information. You can format date and time serial numbers using date and time formats or number formats because date/time serial numbers are stored as floating-point values.
To format dates and times, you can use either the commonly used format that have been predefined or create user-defined time formats using standard meaning of each:
The following list shows the predefined data format names you can use and the meaning of each.
General Display a date and/or time. for real numbers, display a date and time.(e.g. 4/3/93 03:34 PM); If there is no fractional part, display only a date (e.g. 4/3/93); if there is no integer part, display time only (e.g. 03:34 PM).
Long Date Display a Long Date, as defined in the International section of the Control Panel.
Medium Display a date in the same form as the Short Date, as defined in the international section of the Control Panel, except spell out the month abbreviation.
Short Date Display a Short Date, as defined in the International section of the Control Panel.
Long Time Display a Long Time, as defined in the International section of the Control panel. Long Time includes hours, minutes, seconds.
Medium Time Display time in 12-hour format using hours and minuets and the Time AM/PM designator.
Short Time Display a time using the 24-hour format (e.g. 17:45)
This list shows the characters you can use to create user-defined date/time formats.
c Display the date as dddd and display the time as ttttt. in the order.
d Display the day as a number without a leading zero (1-31).
dd Display the day as a number with a leading zero (01-31).
ddd Display the day as an abbreviation (Sun-Sat).
ddddd Display a date serial number as a complete date (including day , month, and year).
w Display the day of the week as a number (1- 7 ).
ww Display the week of the year as a number (1-53).
m Display the month as a number without a leading zero (1-12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm Display the month as a number with a leading zero (01-12). If mm immediately follows h or hh, the minute rather than the month is displayed.
mmm Display the month as an abbreviation (Jan-Dec).
mmmm Display the month as a full month name (January-December).
q display the quarter of the year as a number (1-4).
y Display the day of the year as a number (1-366).
yy Display the day of the year as a two-digit number (00-99)
yyyy Display the day of the year as a four-digit number (100-9999).
h Display the hour as a number without leading zeros (0-23).
hh Display the hour as a number with leading zeros (00-23).
n Display the minute as a number without leading zeros (0-59).
nn Display the minute as a number with leading zeros (00-59).
s Display the second as a number without leading zeros (0-59).
ss Display the second as a number with leading zeros (00-59).
ttttt Display a time serial number as a complete time (including hour, minute, and second) formatted using the time separator defined by the Time Format in the International section of the Control Panel. A leading zero is displayed if the Leading Zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AM/PM Use the 12-hour clock and display an uppercase AM/PM
am/pm Use the 12-hour clock display a lowercase am/pm
A/P Use the 12-hour clock display a uppercase A/P
a/p Use the 12-hour clock display a lowercase a/p
AMPM Use the 12-hour clock and display the contents of the 11:59 string (s1159) in the WIN.INI file with any hour before noon; display the contents of the 2359 string (s2359) with any hour between noon and 11:59 PM. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as it exists in the WIN.INI file. The default format is AM/PM.
The Following are examples of user-defined date and time formats:
Strings can also be formatted with Format[$]. A format expression for strings can have one section or two sections separated by a semicolon.
One section only The format applies to all string data.
Two sections The first section applies to string data, the second to Null values and zero-length strings.
The following characters can be used to create a format expression for strings:
Displays a character or a space. Placeholders are filled from right to left unless there is an ! character in the format string.
& Character placeholder. Display a character or nothing.
! Force placeholders to fill from left to right instead of right to left.
' Format Function Example
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
MyStr Format(MyTime, "h:n:s") ' Returns "17:4:23".
MyStr Format(MyTime, "hh:nn:ss")' Returns "20:04:22 ".
MyStr Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MsgBox Format(23) ' Returns "23".
' User-defined formats.
MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".
End Sub
[statements]
Functionname = expression
[statements]
Functionname = expressionEnd Function
Declares and defines a procedure that can receive arguments and return a value of a specified data type.
When the optional argument list needs to be passed the format is as follows:
([ByVal] variable [As type] [,ByVal] variable [As type] ]Ö])The optional ByVal parameter specifies that the variable is [passed by value instead of by reference (see ``ByRef and ByVal'' in this manual). The optional As type parameter is used to specify the data type. Valid types are String, Integer, Double, Long, and Varaint (see ``Variable Types'' in this manual).
Sub Main
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
Function GetColor2( c% ) As Long
GetColor2 = c% * 25
If c% > 2 Then
GetColor2 = 255 ' 0x0000FF - Red
End If
If c% > 5 Then
GetColor2 = 65280 ' 0x00FF00 - Green
End If
f c% > 8 Then
GetColor2 = 16711680 ' 0xFF0000 - Blue
End If
End Function
Global Const GloConst = 142 '
Const MyConst = 122 'Global to all procedures is a module
Sub Main ()
Dim Answer, Msg, NL ' Declare variables.
Const PI = 3.14159
NL = Chr(10) ' Define newline.
CurPath = CurDir() ' Get current path.
ChDir "\"
Msg = "The current directory has been changed to "
Msg = Msg & CurDir() & NL & NL & "Press OK to change back "
Msg = Msg & "to your previous default directory."
Answer = MsgBox(Msg) ' Get user response.
ChDir CurPath ' Change back to user default.
Msg = "Directory changed back to " & CurPath & "."
MsgBox Msg ' Display results.
myvar =myConst + PI + GloConst
Print MyVar
End Sub
Return
Branches to and returns from subroutines.
Sub Main
x = 4
print x
print "hello"
Gosub fred
print "Joe"
Exit Sub
Fred:
print "there"
Return
End Sub
Sub main ()
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping" ,z,y,x
If y > 3 Then
GoTo Label1
End If
Next z
Next y
Next x
Label1:
End Sub
The parameter num can be any valid number. It is rounded to nearest whole number before evaluation.
Sub Main ()
Dim Msg As String, x%
x% = 10
Msg =Str( x%) & " decimal is "
Msg = Msg & Hex(x%) & " in hex "
MsgBox Msg
End Sub
The parameter string is any numeric expressed as a string that can represent a date and time from January 1, 1980 through December 31, 9999.
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
' This section not yet supported
'MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23".
'MyStr = Format(MyTime, "hh:mm:ss AMPM")' Returns "05:04:23 PM".
'MyStr = Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MsgBox Format(23) ' Returns "23".
' User-defined formats.
MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".
End Sub
[statement(s)]
[statement(s)]
[statements(s)]
If conditional Then statementAllows conditional statements to be executed in the code.
Sub IfTest
demo If...Then...Else
Dim msg as String
Dim nl as String
Dim someInt as Integer
nl = Chr(10)
msg = "Less"
someInt = 4
If 5 > someInt Then msg = "Greater" : Beep
MsgBox(msg)
If 3 > someInt Then
msg = "Greater"
Beep
Else
msg = "Less"
End If
MsgBox(msg)
If someInt = 1 Then
msg = "Spring"
ElseIf someInt = 2 Then
msg = "Summer"
ElseIf someInt = 3 Then
msg = "Fall"
ElseIf someInt = 4 Then
msg = "Winter"
Else
msg = "Salt"
End If
MsgBox(msg)
End Sub
The input function has two parameters n and filenumber. n is the number of bytes to be read from a file and filenumber is the number used in the open statement when the file was opened.
Sub Main
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
MyStr = Input(10, #1) ' Get ten characters.
MsgBox MyStr
Loop
Close #1 ' Close file.
End Sub
Prompt is string that is displayed usually to ask for input type or information.
Title is a string that is displayed at the top of the input dialog box.
Default is a string that is displayed in the text box as the default entry.
Xpos and Ypos and the x and y coodinates of the relative location of the inpur dialog box.
Sub Main ()
Title$ = "Greetings"
Prompt$ = "What is your name?"
Default$ = ""
X% = 2000
Y% = 4000
N$ = InputBox$(Prompt$, Title$, Default$, X%, Y%)
End Sub
The numbegin parameter is not optional and sets the starting point of the search. numbegin must be a valid positive integer no greater than 65,535.
string1 is the string being searched and string2 is the string we are looking for.
Example
Sub Main ()
B$ = "Good Bye"
A% = InStr(2, B$, "Bye")
C% = Instr(3, B$, "Bye")
End Sub
' This sample explores the concept of an empty variant
Sub Main
Dim x ' Empty
x = 5 ' Not Empty - Long
x = Empty ' Empty
y = x ' Both Empty
MsgBox x & " IsEmpty: " & IsEmpty(x)
End Sub
The parameter v can be any variant. IsNull returns a TRUE if v contains NULL. If isNull returns a FALSE the NULL the variant expression is not NULL.
The NULL value is special because it indicates the that the v parameter contains no data. This is different from a null-string, which is a zero length string and an empty string which has not yet been initialized.
The parameter v can be any variant, numeric value, Date or string (if the string can be interpreted as a numeric).
Sub Form_Click ()
Dim TestVar ' Declare variable.
TestVar = InputBox("Please enter a number, letter, or symbol.")
If IsNumeric(TestVar) Then ' Evaluate variable.
MsgBox "Entered data is numeric." Message if number.
Else
MsgBox "Entered data is not numeric." ' Message if not.
End If
End Sub
Const NumberOfFiles = 3
Sub Main ()
Dim Msg ' Declare variable.
Call MakeFiles() ' Create data files.
Msg = "Several test files have been created on your disk. You may see "
Msg = Msg & "them by switching tasks. Choose OK to remove the test files."
MsgBox Msg
For I = 1 To NumberOfFiles
Kill "TEST" & I ' Remove data files from disk.
Next I
End Sub
Sub MakeFiles ()
Dim I, FNum, FName ' Declare variables.
For I = 1 To NumberOfFiles
FNum = FreeFile ' Determine next file number.
FName = "TEST" & I
Open FName For Output As FNum ' Open file.
Print #FNum, "This is test #" & I ' Write string to file.
Print #FNum, "Here is another "; "line"; I
Next I
Close ' Close all files.
Kill FName
End Sub
' This example demonstrates some of the features of arrays. The lower bound
' for an array is 0 unless it is specified or option base has set as is
' done in this example.
Option Base 1
Sub Main
Dim a(10) As Double
MsgBox "LBound: " & LBound(a) & " UBound: " & UBound(a)
Dim i As Integer
For i = 0 to 3
a(i) = 2 + i * 3.1
Next i
Print a(0),a(1),a(2), a(3)
End Sub
' This example uses the LTrim and RTrim functions to strip leading and
' trailing spaces, respectively, from a string variable. It
' uses the Trim function alone to strip both types of spaces.
' LCase and UCase are also shown in this example as well as the use
' of nested function calls
Sub Main
MyString = " <-Trim-> " ' Initialize string.
TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ".
MsgBox "|" & TrimString & "|"
TrimString = LCase(RTrim(MyString)) ' TrimString = " <-trim->".
MsgBox "|" & TrimString & "|"
TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->".
MsgBox "|" & TrimString & "|"
' Using the Trim function alone achieves the same result.
TrimString = UCase(Trim(MyString)) ' TrimString = "<-TRIM->".
MsgBox "|" & TrimString & "|"
End Sub
Left returns a Variant, Left$ returns a String
Sub Main ()
Dim LWord, Msg, RWord, SpcPos, UsrInp ' Declare variables.
Msg = "Enter two words separated by a space."
UsrInp = InputBox(Msg) ' Get user input.
print UsrInp
SpcPos = InStr(1, UsrInp, " ") ' Find space.
If SpcPos Then
LWord = Left(UsrInp, SpcPos - 1) ' Get left word.
print "LWord: "; LWord
RWord = Right(UsrInp, Len(UsrInp) - SpcPos) ' Get right word.
Msg = "The first word you entered is " & LWord
Msg = Msg & "." & " The second word is "
Msg = "The first word you entered is <" & LWord & ">"
Msg = Msg & RWord & "."
Else
Msg = "You didn't enter two words."
End If
MsgBox Msg ' Display message.
MidTest = Mid("Mid Word Test", 4, 5)
Print MidTest
End Sub
Sub Main ()
A$ = "Cypress Enable"
StrLen% = Len(A$) 'the value of StrLen is 14
MsgBox StrLen%
End Sub
Let is an optional keyword that is rarely used. The Let statement is required in older versions of BASIC.
Sub Form_Click ()
Dim Msg, Pi ' Declare variables.
Let Pi = 4 * _Atn(1) ' Calculate Pi.
Msg = "Pi is equal to " & Str(Pi)
MsgBox Msg ' Display results.
End Sub
The parameter filenumber is used in the open statement to open the file. The parameter name is the name of a variable used to hold the line of text from the file.
' Line Input # Statement Example
' This example uses the Line Input # statement to read a line from a
' sequential file and assign it to a variable. This example assumes that
' TESTFILE is a text file with a few lines of sample data.
Sub Main
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
Line Input #1, TextLine ' Read line into variable.
Print TextLine ' Print to Debug window.
Loop
Close #1 ' Close file.
End Sub
The parameter num must be greater than zero and be a valid number.
Sub Form_Click ( )
Dim I, Msg, NL
NL = Chr(13) & Chr(10)
Msg = Exp(1) & NL
For I = 1 to 3
Msg = Msg & Log(Exp(1) ^ I ) & NL
Next I
MsgBox Msg
End Sub
Sub Main ()
Dim LWord, Msg, RWord, SpcPos, UsrInp ' Declare variables.
Msg = "Enter two words separated by a space."
UsrInp = InputBox(Msg) ' Get user input.
print UsrInp
SpcPos = InStr(1, UsrInp, " ") ' Find space.
If SpcPos Then
LWord = Left(UsrInp, SpcPos - 1) ' Get left word.
print "LWord: "; LWord
RWord = Right(UsrInp, Len(UsrInp) - SpcPos) ' Get right word.
Msg = "The first word you entered is " & LWord
Msg = Msg & "." & " The second word is "
Msg = "The first word you entered is <" & LWord & ">"
Msg = Msg & RWord & "."
Else
Msg = "You didn't enter two words."
End If
MsgBox Msg ' Display message.
MidTest = Mid("Mid Word Test", 4, 5)
Print MidTest
End Sub
' Format Function Example
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
End Sub
The parameter path is a string expression that must contain fewer than 128 characters.
Sub Main
Dim DST As String
DST = "t1"
mkdir DST
mkdir "t2"
End Sub
Sub Main
MyDate = "03/03/96"
print MyDate
x = Month(MyDate)
print x
End Sub
The first parameter msg is the string displayed in the dialog box as the message. The second and third parameters are optional and respectively designate the type of buttons and the title displayed in the dialog box.
MsgBox Function returns a value indicating which button the user has chosen; the MsgBox statement does not.
The first group of values (1-5) describes the number and type of buttons displayed in the dialog box. The second group (16, 32, 48, 64) describes the icon style. The third group (0, 256, 512) determines which button is the default, and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the argument type, use only one number from each group. If omitted, the default value for type is 0.
title:String expression displayed in the title bar of the dialog box. If you omit the argument title, MsgBox has no default title.
The value returned by the MsgBox function indicates which button has been selected, as shown:
If the dialog box displays a Cancel button, pressing the Esc key has the same effect as choosing Cancel.
Sub Main
Dim DgDef, Msg, Response, Title ' Declare variables.
Title = "MsgBox Sample Question"
Msg = "This is a sample of Close Without Saving?."
Msg = Msg & " Do you want to continue?"
DgDef = MB_YESNOCANCEL + MB_ICONQUESTION + MB_DEFBUTTON3
Response = MsgBox(Msg, DgDef, Title) ' Get user response.
If Response = IDYES Then ' Evaluate response
Msg = "You chose Yes." ' and take appropriate
ElseIf Response = IDCANCEL Then
Msg = "You chose Cancel"
Else ' action.
Msg = "You chose No or pressed Enter."
End If
MsgBox Msg ' Display action taken.
End Sub
The parameters oldname and newname are string that can optionally contain a path.
Sub Main
Name "testfile" As "newtest"
End Sub
The Now function returns a Variant data type containing a date and time that are stored internally as a double. The number is a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2. Numbers to the left of the decimal point represent the date and numbers to the right represent the time.
Sub Main ()
Dim Today
Today = Now
End Sub
Sub Main ()
Dim Msg, Num ' Declare variables.
Num = InputBox("Enter a number.") ' Get user input.
Msg = Num & " decimal is &O"
Msg = Msg & Oct(Num) & " in octal notation."
MsgBox Msg ' Display results.
End Sub
Sub Main ()
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
TEXT 10, 10, 28, 12, "Name:"
TEXTBOX 42, 10, 108, 12, .nameStr
TEXTBOX 42, 24, 108, 12, .descStr
CHECKBOX 42, 38, 48, 12, "&CHECKME", .checkInt
OKBUTTON 42, 54, 40, 12
End Dialog
Dim Dlg1 As DialogName1
Dialog Dlg1
MsgBox Dlg1.nameStr
MsgBox Dlg1.descStr
MsgBox Dlg1.checkInt
End Sub
The line parameter refers to a label. That label must be present in the code or an error is generated.
Sub Main
On Error GoTo dude
Dim x as object
x.draw ' Object not set
jpe ' Undefined function call
print 1/0 ' Division by zero
Err.Raise 6 ' Generate an "Overflow" error
MsgBox "Back"
MsgBox "Jack"
Exit Sub
dude:
MsgBox "HELLO"
Print Err.Number, Err.Description
Resume Next
MsgBox "Should not get here!"
MsgBox "What?"
End SubErrors can be raised with the syntax:
Err.Raise x
The list below shows the corresponding descriptions for the defined values of x.
10: "Array is fixed or temporarily locked";
17: "Can't perform requested operation";
18: "User interrupt occurred";
35: "Sub, Function, or Property not defined";
47: "Too many DLL application clients";
49: "Bad DLL calling convention";
52: "Bad file name or number";
74: "Can't rename with different drive";
91: "Object variable or With block variable not set";
92: "For loop not initialized";
429: "OLE Automation server cannot create object";
430: "Class doesn't support OLE Automation";
432: "File name or class name not found during OLE Automation operation";
438: "Object doesn't support this property or method";
443: "OLE Automation object does not have a default value";
445: "Object doesn't support this action";
446: "Object doesn't support named arguments";
447: "Object doesn't support current local setting";
448: "Named argument not found";
450: "Wrong number of arguments";
451: "Object not a collection";
444: "Method not applicable in this context";
453: "Specified DLL function not found";
460: "Invalid Clipboard format";
461: "Specified format doesn't match format of data";
480: "Can't create AutoRedraw image";
483: "Printer driver does not supported specified property";
484: "Problem getting printer information from the system.";
// Make sure the printer is setup up correctly.
You must open a file before any I/O operation can be performed on it. The Open statement has these parts:
If file doesn't exist, it is created when a file is opened for Append, Binary or Output modes.
The argument mode is a reserved word that specifies one of the following file modes.
Append Sequential output mode. Append sets the file pointer to the end of the file. A Print # or Write # statement then extends (appends to) the file.
The argument access is a reserved word that specifies the operations that can be performed on the opened file. If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and a Permission denied error occurs. The Access clause works only if you are using a version of MS-DOS that supports networking (MS-DOS version 3.1 or later). If you use the Access clause with a version of MS-DOS that doesn't support networking, a Feature unavailable error occurs.
The argument access can be one of the following reserved words.
The following example writes data to a test file and reads it back.
Sub Main ()
Open "TESTFILE" For Output As #1 ' Open to write file.
userData1$ = InputBox ("Enter your own text here")
userData2$ = InputBox ("Enter more of your own text here")
Write #1, "This is a test of the Write # statement."
Write #1,userData1$, userData2
Close #1
Open "TESTFILE" for Input As #2 ' Open to read file.
Do While Not EOF(2)
Line Input #2, FileData ' Read a line of data.
Print FileData ' Construct message.
Loop
Close #2 ' Close all open files.
MsgBox "Testing Print Statement" ' Display message.
Kill "TESTFILE" ' Remove file from disk.
End Sub
The Option Base statement is never required. If used, it can appear only once in a module, can occur only in the Declarations section, and must be used before you declare the dimensions of any arrays.
The value of number must be either 0 or 1. The default base is 0.
The To clause in the Dim, Global, and Static statements provides a more flexible way to control the range of an array's subscripts. However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.
The example uses the Option Base statement to override the default base array subscript value of 0.
Option Base 1 ' Module level statement.
Sub Main
Dim A(), Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
ReDim A(20) ' Create an array.
Msg = "The lower bound of the A array is " & LBound(A) & "."
Msg = Msg & NL & "The upper bound is " & UBound(A) & "."
MsgBox Msg ' Display message.
End Sub
The Option explicit statement is used outside of the script in the declarations section. This statement can be contained in a declare file or outside of any script in a file or buffer. If this statement is contained in the middle of a file the rest of the compile buffer will be affected.
Option Explicit
Sub Main
Print y `because y is not explicitly dimmed an error will occur.
End Sub
Number used in an Open statement to open a sequential file. It can be any number of an open file. Note that the number sign (#) preceding filenumber is not optional.
Name of the Basic function optionally used to insert n spaces into the printed output. Multiple use is permitted.
Name of the Basic function optionally used to tab to the nth column before printing expressionlist. Multiple use is permitted.
Numeric and/or string expressions to be written to the file.
Character that determines the position of the next character printed. A semicolon means the next character is printed immediately after the last character; a comma means the next character is printed at the start of the next print zone. Print zones begin every 14 columns. If neither character is specified, the next character is printed on the next line.
If you omit expressionlist, the Print # statement prints a blank line in the file, but you must include the comma. Because Print # writes an image of the data to the file, you must delimit the data so it is printed correctly. If you use commas as delimiters, Print # also writes the blanks between print fields to the file.
The Print # statement usually writes Variant data to a file the same way it writes any other data type. However, there are some exceptions:
If the data being written is a Variant of VarType 0 (Empty), Print # writes nothing to the file for that data item.
If the data being written is a Variant of VarType 1 (Null), Print # writes the literal #NULL# to the file.
If the data being written is a Variant of VarType 7 (Date), Print # writes the date to the file using the Short Date format defined in the WIN.INI file. When either the date or the time component is missing or zero, Print # writes only the part provided to the file.
The following example writes data to a test file.
Sub Main
Dim I, FNum, FName ' Declare variables.
For I = 1 To 3
FNum = FreeFile ' Determine next file number.
FName = "TEST" & FNum
Open FName For Output As FNum ' Open file.
Print #I, "This is test #" & I ' Write string to file.
Print #I, "Here is another "; "line"; I
Next I
Close ' Close all files.
End Sub
The following example writes data to a test file and reads it back.
Sub Main ()
Dim FileData, Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
Open "TESTFILE" For Output As #1 ' Open to write file.
Print #2, "This is a test of the Print # statement."
Print #2 ' Print blank line to file.
Print #2, "Zone 1", "Zone 2" ' Print in two print zones.
Print #2, "With no space between" ; "." ' Print two strings together.
Close
Open "TESTFILE" for Input As #2 ' Open to read file.
Do While Not EOF(2)
Line Input #2, FileData ' Read a line of data.
Msg = Msg & FileData & NL ' Construct message.
MsgBox Msg
Loop
Close ' Close all open files.
MsgBox "Testing Print Statement" ' Display message.
Kill "TESTFILE" ' Remove file from disk.
End Sub
Sub PrintExample ()
Dim Msg, Pi ' Declare variables.
Let Pi = 4 * _Atn(1) ' Calculate Pi.
Msg = "Pi is equal to " & Str(Pi)
MsgBox Msg ' Display results.
Print Pi ' Prints the results in the
' compiler messages window
End Sub
The parameter remark is the text of any comment you wish to include in the code.
Rem This is a remark
Sub Main()
Dim Answer, Msg ' Declare variables.
Do
Answer = InputBox("Enter a value from 1 to 3.")
Answer = 2
If Answer >= 1 And Answer <= 3 Then ' Check range.
Exit Do ' Exit Do...Loop.
Else
Beep ' Beep if not in range.
End If
Loop
MsgBox "You entered a value in the proper range."
End Sub
The parameter stringexpression is the string from which the rightmost characters are returned.
The parameter n is the number of characters that will be returned and must be a long integer.
' The example uses the Right function to return the first of two words
' input by the user.
Sub Main ()
Dim LWord, Msg, RWord, SpcPos, UsrInp ' Declare variables.
Msg = "Enter two words separated by a space."
UsrInp = InputBox(Msg) ' Get user input.
print UsrInp
SpcPos = InStr(1, UsrInp, " ") ' Find space.
If SpcPos Then
LWord = Left(UsrInp, SpcPos - 1) ' Get left word.
print "LWord: "; LWord
RWord = Right(UsrInp, Len(UsrInp) - SpcPos) ' Get right word.
Msg = "The first word you entered is " & LWord
Msg = Msg & "." & " The second word is "
Msg = "The first word you entered is <" & LWord & ">"
Msg = Msg & RWord & "."
Else
Msg = "You didn't enter two words."
End If
MsgBox Msg ' Display message.
End Sub
The parameter path is a string that is the name of the directory to be removed.
' This sample shows the functions mkdir (Make Directory)
' and rmdir (Remove Directory)
Sub Main
Dim dirName As String
dirName = "t1"
mkdir dirName
mkdir "t2"
MsgBox "Directories: t1 and t2 created. Press OK to remove them"
rmdir "t1"
rmdir "t2"
End Sub
The parameter number must be a valid numeric expression.
'Rnd Function Example
'The example uses the Rnd function to simulate rolling a pair of dice by
'generating random values from 1 to 6. Each time this program is run,
Sub Main ()
Dim Dice1, Dice2, Msg ' Declare variables.
Dice1 = CInt(6 * Rnd() + 1) ' Generate first die value.
Dice2 = CInt(6 * Rnd() + 1) ' Generate second die value.
Msg = "You rolled a " & Dice1
Msg = Msg & " and a " & Dice2
Msg = Msg & " for a total of "
Msg = Msg & Str(Dice1 + Dice2) & "."
MsgBox Msg ' Display message.
End Sub
The parameter number must be a valid numeric expression.
' Format Function Example
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
'This section not yet supported
MsgBox Format(MyTime, "h:n:s") ' Returns "17:4:23".
MsgBox Format(MyTime, "hh:nn:ss")' Returns "05:04:23".
MsgBox Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MsgBox Format(23) ' Returns "23".
' User-defined formats.
MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".
End Sub
Seek returns a number that represents the byte position where the next operation is to take place. The first byte in the file is at position 1.
Sub Main
Open "TESTFILE" For Input As #1 ' Open file for reading.
Do While Not EOF(1) ' Loop until end of file.
MyChar = Input(1, #1) ' Read next character of data.
Print Seek(1) ' Print byte position .
Loop
Close #1 ' Close file.
End Sub
Seek statement sets the position in a file for the next read or write
Sub Main
Open "TESTFILE" For Input As #1 ' Open file for reading.
For i = 1 To 24 Step 3 ' Loop until end of file.
Seek #1, i ' Seek to byte position
MyChar = Input(1, #1) ' Read next character of data.
Print MyChar 'Print character of data
Next i
Close #1 ' Close file.
End Sub
Select Case testvar
Case var1
Statement Block
Case var2
Statement Block
Case Else
Statement Block
End Select
' This rather tedious test shows nested select statements and if uncommented,
' the exit for statement
Sub Test ()
For x = 1 to 5
print x
Select Case x
Case 2
Print "Outer Case Two"
Case 3
Print "Outer Case Three"
' Exit For
Select Case x
Case 2
Print "Inner Case Two"
Case 3
Print "Inner Case Three"
' Exit For
Case Else ' Must be something else.
Print "Inner Case Else:", x
End Select
Print "Done with Inner Select Case"
Case Else ' Must be something else.
Print "Outer Case Else:",x
End Select
Next x
Print "Done with For Loop"
End Sub
The SendKeys statement has two parameters. The first parameter keys is a string and is sent to the active window. The second parameter wait is optional and if omitted is assumed to be false. If wait is true the keystrokes must be processed before control is returned to the calling procedure.
Sub Main ()
Dim I, X, Msg ' Declare variables.
X = Shell("Calc.exe", 1) ' Shell Calculator.
For I = 1 To 5 ' Set up counting loop.
SendKeys I & "{+}", True ' Send keystrokes to Calculator
Next I ' to add each value of I.
Msg = "Choose OK to close the Calculator."
MsgBox Msg ' Display OK prompt.
AppActivate "Calculator" ' Return focus to Calculator.
SendKeys "%{F4}", True ' Alt+F4 to close Calculator.
End Sub
The shell function has two parameters. The first one, app is the name of the program to be executed. The name of the program in app must include a .PIF, .COM, .BAT, or .EXE file extension or an error will occur. The second argument, style is the number corresponding to the style of the window . It is also optional and if omitted the program is opened minimized with focus.
Minimized with focus (default) 2
Return value: ID, the task ID of the started program.
' This example uses Shell to leave the current application and run the
' Calculator program included with Microsoft Windows; it then
' uses the SendKeys statement to send keystrokes to add some numbers.
Sub Main ()
Dim I, X, Msg ' Declare variables.
X = Shell("Calc.exe", 1) ' Shell Calculator.
For I = 1 To 5 ' Set up counting loop.
SendKeys I & "{+}", True ' Send keystrokes to Calculator
Next I ' to add each value of I.
Msg = "Choose OK to close the Calculator."
MsgBox Msg ' Display OK prompt.
AppActivate "Calculator" ' Return focus to Calculator.
SendKeys "%{F4}", True ' Alt+F4 to close Calculator.
End Sub
Sub Main ()
pi = 4 * Atn(1)
rad = 90 * (pi/180)
x = Sin(rad)
print x
End Sub
The parameter number can be any valid integer and determines the number of blank spaces.
' This sample shows the space function
Sub Main
MsgBox "Hello" & Space(20) & "There"
End Sub
The parameter num must be a valid number greater than or equal to zero.
Sub Form_Click ()
Dim Msg, Number ' Declare variables.
Msg = "Enter a non-negative number."
Number = InputBox(Msg) ' Get user input.
If Number < 0 Then
Msg = "Cannot determine the square root of a negative number."
Else
Msg = "The square root of " & Number & " is "
Msg = Msg & Sqr(Number) & "."
End If
MsgBox Msg ' Display results.
End Sub
' This example shows how to use the static keyword to retain the value of
' the variable i in sub Joe. If Dim is used instead of Static then i
' is empty when printed on the second call as well as the first.
Sub Main
For i = 1 to 2
Joe 2
Next i
End Sub
Sub Joe( j as integer )
Static i
print i
i = i + 5
print i
End Sub
The Stop statement can be placed anywhere in your code.
Sub main ()
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping" ,z,y,x
Next z
Next y
Stop
Next x
End Sub
Sub main ()
Dim msg
a = -1
msgBox "Num = " & Str(a)
MsgBox "_Abs(Num) =" & Str(_Abs(a))
End Sub
String is used to create a string that consists of one character repeated over and over.
Dim [variable(s)]
[statementblock]
[Exit Function]
End Sub
Declares and defines a Sub procedures name, parameters and code.
When the optional argument list needs to be passed the format is as follows:
([ByVal] variable [As type] [,ByVal] variable [As type] ]...])
The optional ByVal parameter specifies that the variable is [passed by value instead of by reference (see ``ByRef and ByVal'' in this manual). The optional As type parameter is used to specify the data type. Valid types are String, Integer, Double, Long, and Varaint (see ``Variable Types'' in this manual).
Sub Main
Dim DST As String
DST = "t1"
mkdir DST
mkdir "t2"
End Sub
The parameter angle must be a valid angle expressed in radians.
' This sample program show the use of the Tan function
Sub Main ()
Dim Msg, Pi ' Declare variables.
Pi = 4 * Atn(1) ' Calculate Pi.
Msg = "Pi is equal to " & Pi
MsgBox Msg ' Display results.
x = Tan(Pi/4)
MsgBox x & " is the tangent of Pi/4"
End Sub
Sub Main ()
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
TEXT 10, 10, 28, 12, "Name:"
TEXTBOX 42, 10, 108, 12, .nameStr
TEXTBOX 42, 24, 108, 12, .descStr
CHECKBOX 42, 38, 48, 12, "&CHECKME", .checkInt
OKBUTTON 42, 54, 40, 12
End Dialog
Dim Dlg1 As DialogName1
Dialog Dlg1
MsgBox Dlg1.nameStr
MsgBox Dlg1.descStr
MsgBox Dlg1.checkInt
End Sub
Sub Main ()
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
TEXT 10, 10, 28, 12, "Name:"
TEXTBOX 42, 10, 108, 12, .nameStr
TEXTBOX 42, 24, 108, 12, .descStr
CHECKBOX 42, 38, 48, 12, "&CHECKME", .checkInt
OKBUTTON 42, 54, 40, 12
End Dialog
Dim Dlg1 As DialogName1
Dialog Dlg1
MsgBox Dlg1.nameStr
MsgBox Dlg1.descStr
MsgBox Dlg1.checkInt
End Sub
' This example shows time function and the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
x = Time$(Now)
Print x
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
MsgBox Format(MyTime, "h:n:s") ' Returns "17:4:23".
MsgBox Format(MyTime, "hh:nn:ss")' Returns "05:04:23 ".
MsgBox Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MsgBox Format(23) ' Returns "23".
' User-defined formats.
MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".
End Sub
ElapseTime = TimeSerial(``23:59:59'')
Midnight = TimeValue(``23:59:59'')
Ltrim, Rtrim and Trim all return a string
Rtrim removes trailing spaces.
Trim removes leading and trailing spaces.
' This example uses the LTrim and RTrim functions to strip leading and
' trailing spaces, respectively, from a string variable. It
' uses the Trim function alone to strip both types of spaces.
' LCase and UCase are also shown in this example as well as the use
' of nested function calls
Sub Main
MyString = " <-Trim-> " ' Initialize string.
TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ".
MsgBox "|" & TrimString & "|"
TrimString = LCase(RTrim(MyString)) ' TrimString = " <-trim->".
MsgBox "|" & TrimString & "|"
TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->".
MsgBox "|" & TrimString & "|"
' Using the Trim function alone achieves the same result.
TrimString = UCase(Trim(MyString)) ' TrimString = "<-TRIM->".
MsgBox "|" & TrimString & "|"
End Sub
[ elementname As typename]
. . .
Defines a user-defined data type containing one or more elements.
The Type statement has these parts:
Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere in your script. Use Dim or Static to declare a variable of a user-defined type. Line numbers and line labels aren't allowed in Type...End Type blocks.
User-defined types are often used with data records because data records frequently consist of a number of related elements of different data types. Arrays cannot be an element of a user defined type in Enable.
' This sample shows some of the features of user defined typesUser Defined Types
Type type1
a As Integer
d As Double
s As String
End Type
Type type2
a As String
o As type1
End Type
Type type3
b As Integer
c As type2
End Type
Dim type2a As type2
Dim type2b As type2
Dim type1a As type1
Dim type3a as type3
Sub Form_Click ()
a = 5
type1a.a = 7472
type1a.d = 23.1415
type1a.s = "YES"
type2a.a = "43 - forty three"
type2a.o.s = "Yaba Daba Doo"
type3a.c.o.s = "COS"
type2b.a = "943 - nine hundred and forty three"
type2b.o.s = "Yogi"
MsgBox type1a.a
MsgBox type1a.d
MsgBox type1a.s
MsgBox type2a.a
MsgBox type2a.o.s
MsgBox type2b.a
MsgBox type2b.o.s
MsgBox type3a.c.o.s
MsgBox a
End Sub
' This example demonstrates some of the features of arrays. The lower bound
' for an array is 0 unless it is specified or option base is set it as is
' done in this example.
Option Base 1
Sub Main
Dim a(10) As Double
MsgBox "LBound: " & LBound(a) & " UBound: " & UBound(a)
Dim i As Integer
For i = 1 to 3
a(i) = 2 + i
Next i
Print a(1),a(1),a(2), a(3)
End Sub
' This example uses the LTrim and RTrim functions to strip leading and
' trailing spaces, respectively, from a string variable. It
' uses the Trim function alone to strip both types of spaces.
' LCase and UCase are also shown in this example as well as the use
' of nested function calls
Sub Main
MyString = " <-Trim-> " ' Initialize string.
TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ".
MsgBox "|" & TrimString & "|"
TrimString = LCase(RTrim(MyString)) ' TrimString = " <-trim->".
MsgBox "|" & TrimString & "|"
TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->".
MsgBox "|" & TrimString & "|"
' Using the Trim function alone achieves the same result.
TrimString = UCase(Trim(MyString)) ' TrimString = "<-TRIM->".
MsgBox "|" & TrimString & "|"
End Sub
Sub main
Dim Msg
Dim YourVal As Double
YourVal = Val(InputBox$("Enter a number"))
Msg = "The number you entered is: " & YourVal
MsgBox Msg
End Sub
The parameter varname is a variant data type.
If VarType(x) = 5 Then Print "Vartype is Double" 'Display variable type
Sub Main
Const Max = 5
Dim A(5) As String
A(1) = "Programmer"
A(2) = "Engineer"
A(3) = "President"
A(4) = "Tech Support"
A(5) = "Sales"
Exchange = True
While Exchange
Exchange = False
For I = 1 To Max
MsgBox A(I)
Next I
Wend
[STATEMENTS]
The With statement allows you to perform a series of commands or statements on a particular object without again referring to the name of that object. With statements can be nested by putting one With block within another With block. You will need to fully specify any object in an inner With block to any member of an object in an outer With block.
' This sample shows some of the features of user defined types and the with
' statement
Type type1
a As Integer
d As Double
s As String
End Type
Type type2
a As String
o As type1
End Type
Dim type1a As type1
Dim type2a As type2
Sub Main ()
With type1a
.a = 65
.d = 3.14
End With
With type2a
.a = "Hello, world"
With .o
.s = "Goodbye"
End With
End With
type1a.s = "YES"
MsgBox type1a.a
MsgBox type1a.d
MsgBox type1a.s
MsgBox type2a.a
MsgBox type2a.o.s
End Sub
A comma delimited list of the supplied parameters is written to the indicated file. If no parameters are present, the newline character is all that will be written to the file.
Sub Main ()
Open "TESTFILE" For Output As #1 ' Open to write file.
userData1$ = InputBox ("Enter your own text here")
userData2$ = InputBox ("Enter more of your own text here")
Write #1, "This is a test of the Write # statement."
Write #1,userData1$, userData2
Close #1
Open "TESTFILE" for Input As #2 ' Open to read file.
Do While Not EOF(2)
Line Input #2, FileData ' Read a line of data.
Print FileData ' Construct message.
Loop
Close #2 ' Close all open files.
MsgBox "Testing Print Statement" ' Display message.
Kill "TESTFILE" ' Remove file from disk.
End Sub
The parameter serial# is a string that represents a date.
If serial is a Null, this function returns a Null.
Sub Main
MyDate = "11/11/94"
x = Year(MyDate)
print x
End Sub