Functions
Contents
- Using Functions and Procedures
- Defining parameterized Functions and Procedures
- Passing Parameters to functions and procedures
- Calling Procedures in external DLLs
- Enable Basic Functions
- Dates and Times
- Date
- Day
- Hour
- IsDate
- Minute
- Month
- Now
- Second
- Time
- Year
- IO
- ChDir
- ChDrive
- Chr
- Close #
- CurDir
- EOF
- Erase
- FileLen
- FileCopy
- Input #
- Kill
- Line Input #
- MkDir
- Open #
- Print #
- RmDir
- Seek #
- Write #
- Maths
- Cos
- Exp
- Log
- Not
- Oct
- Rnd
- Sin
- Sqr
- Tan
- Strings
- LCase
- Len
- Left
- Mid
- Right
- Str
- Trim, LTrim, RTrim
- UCase
- Enable Basic Extensions
- AltKeyDown
- ConfirmNoYes
- ConfirmNoYesCancel
- GetCurrentWindowHandle
- ResetCursor
- RunApplication
- SetCursorBusy
- ShiftKeyDown
- ShowError
- ShowInfo
- ShowWarning
Parent page: EnableBasic
In Enable Basic, there are two main types of language elements:
- Functions - these elements perform an action and then return a value.
- Procedures - these perform actions but do not have any return value.
This section of the Enable Basic Reference details the functions and procedures supported by the Enable Basic scripting language.
Using Functions and Procedures
An Enable Basic macro script must define at least one procedure that defines the main program code. However, other procedures and functions can be defined that can be called by the code. Procedures that are called by other procedures or functions are called subprocedures.
The essentials:
- As with the main program code, subprocedures are defined within a
Sub...End Sub
statement block. - Functions are defined within a
Function...End Function
statement block. - Any subprocedures or functions used in a macro script must be defined after the main program procedure definition.
- To use (known as "calling") a function or subprocedure, include the name of the function or procedure in a statement in the same way that the built-in Enable Basic functions and procedures are used. If the function or procedure requires parameters, then these must be included in the calling statement.
- Both functions and subprocedures can be defined to accept parameters, but only functions can be defined to return a value to the calling statement.
- When calling a function, the statement containing the function call must be able to handle the return value. This is usually done by assigning the return value to a variable, or by using the return value in a calculated expression.
- Any name may be assigned when defining functions and procedures, as long as it conforms to the standard Enable Basic naming conventions.
Defining parameterized Functions and Procedures
Both the functions and subprocedures defined in a macro script can be declared to accept parameters. Additionally, functions are defined to return a value.
To define a parameterized function or subprocedure, list the variable names to be used to store the parameters as part of a Sub or Function
statement. For example, the following code fragment defines a subprocedure that accepts two parameters, storing them in variables Param1
and Param2
respectively:
Sub mySub(Param1, Param2)
To call this subprocedure, the statement form woul be:
mySub Var1, Var2
...where Var1
and Var2
are to be passed to the subprocedure mySub
.
Optionally in a Sub
or Function
, the data type of the parameters can be specified by including the As type
clause in the parameter list. For example:
Sub mySub(Param1 As Integer, Param2 As String)
A valid call to this function would be:
mySub 5, "Hello"
As well as defining the data type of the parameters to be passed, how the parameters will be passed to the subroutine or function can be nominated. Enable Basic provides two methods of passing parameters to subprocedures or functions:
ByRef
- passes a reference to the variable passed and allows the subprocedure or function to make changes to the actual variables that are passed in as parameters. This is the default method of passing parameters and is used if the method is not explicitly declared.ByVal
- passes the value of the variable only. The subprocedure or function can use this value, but the original variable passed is not altered.
For more information on using the ByRef and ByVal keywords, see the following section, Passing Parameters to Enable Basic Functions and Procedures.
Passing Parameters to functions and procedures
When a function or subprocedure that can accept parameters is defined in a script, variables can be passed to the function or subprocedure in two ways: by reference or by value.
To declare the method that parameters are passed, use the ByRef
or ByVal
keywords in the parameter list when defining the function or subprocedure in a Sub
or Function
statement. For example, the following code fragment defines a subprocedure that accepts two parameters. The first is passed by value and the second by reference:
Sub Test (ByVal Param1 As Integer , ByRef B As String)
The difference between the two methods is how the passed variable is handled:
ByRef
passes a reference to the variable, and allows the subprocedure or function to make changes to the actual variables that are passed in as parameters — this is the default method of passing parameters and is used if the method is not explicitly declared.ByVal
passes the value of the variable only. The subprocedure or function can use this value, but the original variable passed is not altered.
The following examples illustrate the differences between methods. The main procedure is as follows:
Sub Main Dim X As Integer, Y As String X = 45 : Y = "Number" Test X, Y ' Call to a subprocedure called Test. Print X, Y End Sub
The above procedure includes a call to subprocedure Test
. If the subprocedure is defined as follows:
Sub Test (ByRef A As Integer , ByRef B As String) B = B & " = " & A : A = 10*A End Sub
...then the variables X
and Y
in the main procedure are then referenced directly by the subprocedure. The result is that the values of X
and Y
are altered by the subprocedure, so that after Test
is executed X = 450 and Y
= "Number = 45".
If, however, the subprocedure is defined as follows:
Sub Test (ByVal A As Integer , ByVal B As String) B = B & " = " & A : A = 10*A End Sub
...then after Test is executed X
= 45 and Y
= "Number" — that is, they remain unchanged.
Alternatively, if the subprocedure is defines as follows:
Sub Test (ByRef A As Integer , ByVal B As String) B = B & " = " & A : A = 10*A End Sub
...then after Test
is executed, X
= 450 and Y
= "Number". Because Y
was passed by value, it remains unchanged.
The ByRef
setting of a function or subprocedure can be overridden by putting parentheses around a variable name in the calling statement. Calling Test
with the following statement:
Test (X), Y
...would pass the variable X
by value, regardless of the method defined for that parameter in the procedure definition.
Calling Procedures in external DLLs
A function or procedure that is in an external dynamic linked library (DLL) can be called from an Enable Basic script by first defining the function or procedure using the Declare
statement.
The Declare
statement must by placed outside the main procedure in the Global Declarations section of the file. All declarations of external functions and procedures are Global. and accessible by all procedures and functions. If the call to the DLL returns a value it should be declared as a function, or otherwise declared as a subprocedure.
The following code segment declares a function called GetPrivateProfileString
which resides in Kernel32.dll
, which is part of the Windows system. The function takes six parameters and returns an integer value.
Declare Function GetPrivateProfileString Lib "Kernel32" _ (ByVal lpApplicationName As String, ByVal lpKeyName As _ String, ByVal lpDefault As String, ByVal lpReturnedString _ As String, ByVal nSize As Integer, ByVal lpFileName As String)_ As Integer
The following code segment declares a subprocedure called InvertRect
which is in User.dll
— also part of the Windows system. The procedure takes two parameters, and being a subprocedure, it does not return any values.
Declare Sub InvertRect Lib "User" (ByVal hDC As Integer, _ aRect As Rectangle)
Once an external function or procedure is declared, it can be called in the same way as any other internal or user-defined function or procedure.
It is important to note that the Enable Basic interpreter cannot verify that an external DLL function or procedure has been declared using the correct name or parameters. Nor can it determine if the correct values have been passed to the external DLL. Before declaring and using an external function or subprocedure, it's important to understand the workings of the external function/procedure.
Enable Basic Functions
The following section details the Functions supported by Enable Basic, organized by application categories.
Dates and Times
Date
Description
This function returns a Date
data type that contains the current date in the system short date format.
Syntax
Date
Parameters
No parameters.
Example
This example displays the current date in two formats.
Sub Main Dim Msg, NL, d1, d2 NL = Chr(10) ' Define newline. d1 = Date d2 = Format (Date, "d-mmmm-yy") Msg = "Date 1 is " & d1 & NL Msg = Msg & "Date 2 is " & d2 & NL MsgBox Msg End Sub
Day
Description
This function returns an integer between 1 and 365, inclusive, that represents the day of the month given in DateVar$
. To check that a string or string expression can be resolved to a valid date, use the IsDate
function.
Syntax
Day(DateVar$)
Parameters
DateVar$
- a string or string expression that can be resolved to a valid date.
Example
The following example displays the current day, month and year is succession.
Sub Main MsgBox "The current day of the month is " & Day(Date) MsgBox "The current month is " & Month(Date) MsgBox "The current year is " & Year(Date) End Sub
Hour
Description
This function returns an integer between 0 and 23 that is the hour of the day, indicated in the parameter TimeVar$
. TimeVar$
must be able to be resolved into a valid time, for example "08:04:23 PM" or "20:04:23". The function returns an Integer data type.
Syntax
Hour(TimeVar$)
Parameters
TimeVar$
- a string expression that represents a valid time.
Example
This example displays the hours, minutes and seconds derived from a time string.
Sub Main MyTime = "08:04:23 PM" MsgBox Second( MyTime ) & " Seconds" ' returns 23 MsgBox Minute( MyTime ) & " Minutes" ' returns 4 MsgBox Hour( MyTime ) & " Hours" ' returns 8 End Sub
IsDate
Description
Returns a value that indicates whether a variant parameter can be converted to a date. The function returns a Boolean TRUE if expression can be resolved to a valid date, or FALSE if it cannot.
Syntax
IsDate(expression)
Parameters
An expression to be validated.
Minute
Description
This function returns an integer between 0 and 59 representing the minute of the hour given in TimeVar$
.TimeVar$
must be able to be resolved into a valid time, for example "08:04:23 PM" or "20:04:23".
Syntax
Minute(TimeVar$)
Parameters
TimeVar$ - a string expression that represents a valid time.
Example
This example displays the hours, minutes and seconds derived from a time string.
Sub Main MyTime = "08:04:23 PM" MsgBox Second( MyTime ) & " Seconds" ' returns 23 MsgBox Minute( MyTime ) & " Minutes" ' returns 4 MsgBox Hour( MyTime ) & " Hours" ' returns 8 End Sub
Month
Description
This function returns an integer between 1 and 12 inclusive, representing the month of the year given in DateVar$
. To check that a string or string expression can be resolved to a valid date, use the IsDate
function.
Syntax
Month(DateVar$)
Parameters
DateVar$
- a string expression that can be resolved to a valid date.
Example
The following example displays the current day, month and year in succession.
Sub Main MsgBox "The current day of the month is " & Day(Date) MsgBox "The current month is " & Month(Date) MsgBox "The current year is " & Year(Date) End Sub
Now
Description
This function returns a Date
data type, which includes both the current date and time values.
Syntax
Now
Parameters
None
Second
Description
Returns an integer between 0 and 59 representing the seconds portion of the time given in TimeVar$
. TimeVar$
must be able to be resolved into a valid time, for example "08:04:23 PM" or "20:04:23".
Syntax
Second(TimeVar$)
Parameters
TimeVar$
- a string or string expression that represents a valid time.
Example
This example displays the hours, minutes and seconds derived from a time string.
Sub Main MyTime = "08:04:23 PM" MsgBox Second( MyTime ) & " Seconds" ' returns 23 MsgBox Minute( MyTime ) & " Minutes" ' returns 4 MsgBox Hour( MyTime ) & " Hours" ' returns 8 End Sub
Time
Description
The function returns the current system time in the default system short time format.
Syntax
Time
Parameters
None
Example
The following example gets the current system time and formats it for display in the Long Time format.
Sub Main ' Returns current system time in the long time format. MsgBox Format(Time, "Long Time") End Sub
Year
Description
The function returns an integer that represents the year given in DateVar$
. To check that a string or string expression can be resolved to a valid date, use the IsDate
function.
Syntax
Year(DateVar$)
Parameters
DateVar$
- a string expression that can be resolved to a valid date.
Example
The following example displays the current day, month and year is succession.
Sub Main MsgBox "The current day of the month is " & Day(Date) MsgBox "The current month is " & Month(Date) MsgBox "The current year is " & Year(Date) End Sub
IO
ChDir
Description
Changes the current default directory.
Syntax
ChDir PathName$
Parameters
PathName$
- a string or string expression, limited to fewer then 128 characters, identifying the path to target directory. If the drive letter is omitted from Pathname$
, the function operates on the current drive.
Notes
To return the current default directory, use the CurDir
and CurDrive
functions.
Example
This example changes to the root directory and then back to the original directory.
Sub Main () Dim Answer, Msg, NL ' Declare variables. NL = Chr(10) ' Define newline. CurPath = CurDir() ' Get current path. ChDir "\" ' Change to root directory Msg = "The current directory has been changed to " Msg = Msg & CurDir() & NL & NL & "Change back." 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
ChDrive
Description
Changes the current default drive.
Syntax
ChDrive Drivename$
Parameters
DriveName$
- a string or string expression that references a valid drive.
Notes
Only a single letter is used by the ChDrive
procedure to identify a target drive. If more than a single character is supplied as an argument, the procedure ignores all but the first character. Therefore the statements ChDrive("D:")
and ChDrive("D")
are equivalent. Both will change to the D: drive, however the colon in the first statement is ignored and is not necessary.
Example
This example changes to G: drive and back.
Sub Main () Dim Msg, NL ' Declare variables. NL = Chr(10) ' Define newline. CurPath = CurDir() ' Get current path. ChDrive "G" ' Change to drive G: Msg = "The current directory has been changed to " Msg = Msg & CurDir() & NL & NL & "Change back." MsgBox Msg ' Get user response. ChDir CurPath ' Change back to user default. Msg = "Directory changed back to " & CurPath & "." MsgBox Msg ' Display results. End Sub
Chr
Description
Converts an integer representing an ASCII character code into the corresponding character.
Syntax
Chr(int)
Parameters
int
- an integer expression which represents an ASCII character code.
Notes
The function returns a string containing a single character whose character code is the int
argument. To convert a single character string to an ASCII code, use the Asc
function.
Example
This example prints all the letters of the alphabet into a message dialog.
Sub ChrExample () Dim X, Msg For X = Asc("A") To Asc("Z") Msg = Msg & Chr(X) Next X MsgBox Msg End Sub
Close #
Description
Closes all active input/output files.
Syntax
Close
Parameters
This procedure takes no parameters
Notes
Whenever a file is opened with the Open
procedure, a Close
statement must be issued after performing all file operations. This ensures the files are properly released by the program.
Example
This example creates three files, writes some text to these files and the closes the files.
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. Print #I, "Here is another "; "line"; I Next I Close ' Close all files. End Sub
CurDir
Description
Returns the full path including drive name to the current directory.
Syntax
CurDir
Parameters
This function takes no parameters.
Notes
The function returns a String data type. The function is read only — to change the current drive and directory use the ChDrive
and ChDir
functions.
Example
The following example displays the current directory in a message box.
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
EOF
Description
Returns a value (0 = false, -1 = true) during file input that indicates whether the end of the file has been reached.
Syntax
EOF(FileNumber)
Parameters
FileNumber
- an integer that is the file number of an open input file.
Notes
The function returns a -1 value if the end of the file has been reached, otherwise it returns 0.
Example
This example uses the Input
function to read 10 characters at a time from a file and display them in a message dialog. This example assumes that TESTFILE
is a text file with a few lines of sample data.
Sub Main Open "TESTFILE" For Input As #1 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
Erase
Description
Reinitializes the elements of a fixed array.
Syntax
Erase arrayname
Parameters
arrayname
- the name of an array variable. Specify the array name only, without any subscripts or parentheses.
Notes
Reinitializing an array sets all elements in the array to 0 for numeric arrays, or a null string for string arrays.
Example
This example defines two arrays, one integer and one string and assigns values to them. The Erase
procedure is then used to reinitialize the arrays.
Sub Main Dim IntArray(2) As Integer, StrArray(2) As String Dim I As Integer ' Initialize the arrays For I = 0 to 2 IntArray(I) = I+1 Next I StrArray(0) = "Goodbye" StrArray(1) = "cruel" StrArray(2) = "world\!" ' Display the arrays Print IntArray(0), IntArray(1), IntArray(2) Print StrArray(0), StrArray(1), StrArray(2) ' Reinitialize the arrays Erase IntArray Erase StrArray ' Redisplay the arrays Print IntArray(0), IntArray(1), IntArray(2) Print StrArray(0), StrArray(1), StrArray(2) End Sub
FileLen
Description
Returns a long integer that is the length of the file in bytes. This function returns a Long data type. If the file does not exist, the function returns -1.
Syntax
FileLen(FileName$)
Parameters
FileName$
- a string or string expression that contains the filename and path of the file to be tested.
Example
The following example displays the size of a config.sys
file.
Sub Main() Dim myFile$, Size& myFile$ = "C:\config.sys" Size& = FileLen(myFile$) If Size& = \-1 Then ' Test that file was found MsgBox "Could not find file." Else MsgBox "Config file is " & Size& & " bytes" End If End Sub
FileCopy
Description
Copies a file from source to destination.
Syntax
FileCopy SourceFile$, DestinationFile$
Parameters
SourceFile$
- a string expression containing the file name, including full path if not in the current directory, of the file to copy.
DestinationFile$
- a string expression containing the path and file name for the copied file.
Notes
For both SourceFile$
and DestinationFile$
you must specify a name for the file, even if the destination file is to be of the same name as the original. If the source or destination is not the current directory, you must specify the path as part of the SourceFile$
and/or DestinationFile$
strings.
Note that it's important to independently determine if the source file exists, as the FileCopy
function does not test for this. If SourceFile$
does not exist, the statement will create a zero length file of the name, at the location given by DestinationFile$
. If DestinationFile$
already exists, it will not be overwritten. If the path specified in DestinationFile$
does not exist, it will not be created.
Example
The following example copies the file test.txt
from the temp1
directory on C: drive to the temp2
directory. The copied file is given the name newname.txt
. The below example assumes C:\temp1\test.txt
exists and that the directory
C:\temp2
has been created.
Sub ExpExample () Dim mySource, myDestination As String mySource = "C:\temp1\test.txt" myDestination = "C:\temp2\newname.txt" FileCopy mySource, MyDestination End Sub
Input #
Description
Input returns a defined number of characters from a sequential file.
Syntax
Input(numBytes , [#]FileNumber)
Parameters
numBytes
- numeric expression representing the number of bytes to be read from the file.
FileNumber
- the file number used in the Open statement to open the file.
Notes
The file referenced by FileNumber
must be opened for input using an Open
statement before it can be used by the Input
function. The function returns a String data type.
Example
This example assumes that a file called TESTFILE
exists in the current directory.
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
Kill
Description
This procedure is used to delete a file from a disk.
Syntax
Kill FileName$
Parameters
FileName$
- a string expression that contains the full filename and path of a file to delete.
Notes
This procedure is only used to remove files. To remove a directory, use the RmDir
procedure.
Example
The following example creates three test files in the current directory, and then deletes them.
Const NumberOfFiles = 3 Sub Main () Dim Msg, J Msg = "Creating test files in the " Msg = Msg & CurDir & " directory." Msg = Msg & Chr(10) & "Files will be deleted after use." If MsgBox(Msg, 1, "Test") = 1 Then Call MakeFiles() ' Create data files. Msg = "Three test files have been created on your disk " Msg = Msg & "in " & CurDir & Chr(10) Msg = Msg & "Choose OK to remove these files." If MsgBox(Msg, 1, "Remove files?") = 1 Then For J = 1 To NumberOfFiles Kill "TEST" & J ' Remove data files from disk. Next J MsgBox "Files have been removed." End If End If End Sub ' Function to generate test files Sub MakeFiles () Dim I, FNum, FName 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 Print #FNum, "Here is another "; "line"; I Next I Close ' Close all files. End Sub
Line Input #
Description
Reads a line from a sequential file into a String or Variant variable.
Syntax
Line Input #FileNumber, VarName
Parameters
FileNumber
- the number used in an Open
statement to open the file.
VarName
- the name of a string or variant variable to hold the line of text.
Notes
The file referred to by FileNumber
must be opened for input using an Open
statement prior to using this function.
Example
This example assumes a file called TESTFILE
exists in the current directory.
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
MkDir
Description
Creates a new directory within an existing directory.
Syntax
MkDir Path$
Parameters
Path$
- a string expression of less than 128 characters that represents the path and name of the directory to create.
Notes
You can only use MkDir
to create a new directory within a directory that already exists. You cannot create multiple directories in a hierarchy with a single MkDir
statement. For example, if the directory C:\TEST
does not exist, then the statement MkDir "C:\TEST\SUBTEST"
would not perform any action. The directory C:\TEST
and then C:\TEST\SUBTEST
would need to be created sequentially.
If Path$
already exists, the procedure performs no action.
Example
This example creates a directory on C: drive called NewDir1
and then creates a subdirectory under this called NewDir2
. The macro then removes the newly created directories.
Sub Main Dim DST As String DST = "C:\NewDir1" If MsgBox("OK to create test directories?", 1, "New Dir") = 1 Then MkDir DST MsgBox "New directory has been created on C:" MkDir "C:\NewDir1\NewDir2" MsgBox "A new subdirectory has been created." If MsgBox("OK to delete test directories?", 1, "Del Dir") = 1 Then RmDir "C:\NewDir1\NewDir2" RmDir DST MsgBox "Test directories removed." End If End If End Sub
Open #
Description
Opens a file for sequential input and output operations.
Syntax
Open FileName$ [For mode] [Access access] As [#]FileNumber
Parameters
FileName$
- a string expression that contains the filename and path.
mode
- keyword that specifies the file mode: Append, Input, Output
access
- keyword that specifies which operations are permitted on the file: Read, Write, Read Write.
FileNumber
- integer expression with a value between 1 and 255, inclusive. When an Open statement is executed, filenumber
is associated with the file as long as it is open. Other I/O statements can use the number to refer to the file.
Notes
A file must be open before any I/O operation can be performed on it. If FileName$
doesn't exist, it is created when a file is opened for Append
or Output
modes. If the file is already opened by another process and the specified type of access is not allowed, the Open
operation fails with a permission denied error.
mode =
Input
- Sequential input mode. Data can be read from the file.
Output
- Sequential output mode. Data can be written to the file.
Append
- Append sets the file pointer to the end of the file. A Print #
or Write #
statement then adds to (appends to) the file.
access =
Read
- Opens the file for reading only.
Write
- Opens the file for writing only.
Read Write
- Opens the file for both reading and writing. This mode is valid only for files opened for Append mode.
Example
The following example creates a file called TESTFILE
in the current directory, gets input from the user, and writes this to the file. The program then reads the data in the file and displays it.
Sub Main () ' Create a test file and write some date to it 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 file." Write #1, userData1$ Write #1, userData2$ Close #1 ' Read the data back from the test file Open "TESTFILE" For Input As #2 ' Open to read file. Msg$ = "" Do While Not EOF(2) Line Input #2, FileData ' Read a line of data. Msg$ = Msg$ & FileData & Chr(10) ' Construct message. Loop Close #2 ' Close all open files. MsgBox Msg$ ' Display file contents Kill "TESTFILE" ' Remove file from disk. End Sub
Print #
Description
Writes data to a sequential file.
Syntax
Print #FileNumber, [OutputList]
Parameters
FileNumber
- the file number associated with the file to print to.
OutputList
- list of expressions to print (see below)
The OutputList argument takes the following format:
[{Spc(n) | Tab[(n)]}] [expression] [charpos]
...where;
Spc(n)
- Used to insert space characters in the output, where n
is the number of space characters to insert.
Tab(n)
- Used to position the insertion point to an absolute column number, where n
is the column number. Use Tab
with no argument to position the insertion point at the beginning of the next print zone.
Expression
- Numeric expressions or string expressions to print.
charpos
- Specifies the insertion point for the next character. Use a semicolon to position the insertion point immediately after the last character displayed. Use Tab(n)
to position the insertion point to an absolute column number. Use Tab
with no argument to position the insertion point at the beginning of the next print zone. If charpos
is omitted, the next character is printed on the next line.
Notes
If you omit OutputList
and include only a list separator after FileNumber
, a blank line is printed to the file. Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon.
The Print #
statement usually writes a Variant data type 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 system Short Date format. When either the date or the time component is missing or zero, Print #
writes only the part provided to the file.
Example
The following example prints lines of date to a sequential 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
RmDir
Description
Removes an existing empty directory.
Syntax
RmDir DirName$
Parameters
DirName$
- a string expression that contains the name and path to the directory to be removed.
Notes
If the directory listed in DirName$
does not exist, the procedure takes no action. If the directory referred to in DirName$
contains files, then no action is taken. To remove a directory it must first be empty.
Example
This example creates a directory on C: drive called NewDir1
and then creates a subdirectory under this called NewDir2
. The macro then removes the newly created directories.
Sub Main Dim DST As String DST = "C:\NewDir1" If MsgBox("OK to create test directories?", 1, "New Dir") = 1 Then MkDir DST MsgBox "New directory has been created on C:" MkDir "C:\NewDir1\NewDir2" MsgBox "A new subdirectory has been created." If MsgBox("OK to delete test directories?", 1, "Del Dir") = 1 Then RmDir "C:\NewDir1\NewDir2" RmDir DST MsgBox "Test directories removed." End If End If End Sub
Seek #
Description
The function form of Seek
returns the byte position of the file pointer in an open file. This marks the current read/write position in the file.
The procedure form of Seek
sets the read/write position of an open file.
Syntax
Seek([#]FileNumber)
Seek [#]FileNumber, Position
Parameters
FileNumber
- a numeric expression that represents a number used in the Open #
statement.
Position
- a numeric expression representing the byte position relative to the beginning of the file.
Notes
The function form of Seek
returns a Long data type. The FileNumber
parameter must reference a currently open file.
Example
The following examples assume that a file called TESTFILE
containing several lines of data exists in the current directory. This example uses the function form of Seek
to print the current byte position.
Sub SeekFunction 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 This example uses the procedure form of Seek to move through the data. Sub SeekProcedure 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
Write #
Description
Writes and formats data to a sequential file that has been opened in Output
or Append
mode.
Syntax
Write #FileNumber [, paramrlist ]
Parameters
FileNumber
- a valid file number that references a file opened with the Open #
statement.
paramlist
- a comma-delimited list of numeric or string expressions to write to the file.
Notes
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.
Example
The following example creates a file called TESTFILE
in the current directory and then gets input from the user and writes this to the file. The program then reads the data in the file and displays it.
Sub Main () ' Create a test file and write some date to it 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 file." Write #1, userData1$ Write #1, userData2$ Close #1 ' Read the data back from the test file Open "TESTFILE" For Input As #2 ' Open to read file. Msg$ = "" Do While Not EOF(2) Line Input #2, FileData ' Read a line of data. Msg$ = Msg$ & FileData & Chr(10) ' Construct message. Loop Close #2 ' Close all open files. MsgBox Msg$ ' Display file contents Kill "TESTFILE" ' Remove file from disk. End Sub
Maths
Cos
Description
Returns the cosine of an angle. The argument must be expressed in radians and must be a valid numeric expression. The function returns a Double data type.
Syntax
Cos (number)
Parameters
number
- a numeric variable, constant or expression.
Example
The example displays the cosine of 1, 2, 3 radians.
Sub Main() Dim I As Single 'Declare variables. For I =1 To 3 Msg = Msg & "Cos(" & I & ")=" Msg = Msg & Cos(I) & " " 'Cos function call Next I MsgBox Msg ' Display results. End Sub
Exp
Description
Returns the base of the natural log raised to a power (e^ num
).
Syntax
Exp(num)
Parameters
num
- number or numeric expression.
Notes
The value of the constant e
is approximately 2.71828
. This function returns a Double data type.
Example
This example calculates the value of the constant e
.
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 End Sub
Log
Description
Returns the natural log of a number.
Syntax
Log(num)
Parameters
num
- a numerical expression. The number must greater than zero.
Notes
The base for the natural log is the constant e
, which is approximately 2.71828
. This function returns a Double data type.
Not
Description
Returns the Boolean opposite of expression.
Syntax
Not(expression)
Parameters
expression
- an expression that resolves to a Boolean TRUE or FALSE.
Notes
The expression parameter must be able to be resolved to a TRUE or FALSE value. A numeric 0 value is the equivalent of a Boolean FALSE. Any non-zero numeric value resolves to a Boolean TRUE.
Oct
Description
Returns the octal value of the decimal parameter. The function returns a String data type which is the octal representation of the argument.
Syntax
Oct(num)
Parameters
num
- a numeric expression.
Rnd
Description
Returns a random number between 0 and 1. The function returns a Double data type whose value is randomized between 0 and 1.
Syntax
Rnd
Parameters
None
Example
The example uses the Rnd
function to simulate rolling a pair of dice by generating random values from 1 to 6.
Sub Main () Dim Dice1, Dice2, Msg, Again Again = True While Again MsgBox "Press OK to roll the dice" Dice1 = CInt(5 * Rnd) + 1 ' Generate first die value. Dice2 = CInt(5 * 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) & "." & Chr(10) Msg = Msg & Chr(10) & "Roll again?" If MsgBox(Msg, 36, "Roll dice") = 7 Then Again = False End If Wend End Sub
Sin
Description
Returns the sine of an angle. The argument must be expressed in radians and must be a valid numeric expression. The function returns a Double data type.
Syntax
Sin(number)
Parameters
number
- a numeric variable, constant or expression.
Example
Sub Main () pi = 4 * Atn(1) rad = 90 * (pi/180) x = Sin(rad) Print x End Sub
Sqr
Description
Returns the square root of a number.
Syntax
Sqr(num)
Parameters
num
- a positive number or numeric expression. The parameter num
must be a valid number greater than or equal to zero.
Notes
The function returns a Double data type representing the square root of num
.
Tan
Description
Returns the tangent of an angle.
Syntax
Tan(number)
Parameters
number
- a numeric expression.
Notes
The argument must be expressed in radians and must be a valid numeric expression. The function returns a Double data type.
Example
The following example calculates the tangent of Pi/4
radians.
Sub Main Dim Msg, Pi Pi = 4 * Atn(1) ' Calculate Pi. Msg = "Pi is equal to " & Pi MsgBox Msg x = Tan(Pi/4) MsgBox x & " is the tangent of Pi/4" End Sub
Strings
LCase
Description
Returns a string in which all letters of the string$
parameter have been converted to lower case.
Syntax
LCase(string$)
Parameters
string$
- a string or string expression.
Notes
The function returns a String data type.
Len
Description
Returns the number of characters in a string.
Syntax
Len(string$)
Parameters
string$
- a string expression.
Notes
The function returns an Integer data type representing the length of the string.
Left
Description
Returns the left most number of characters of a string parameter.
Syntax
Left(string$, chars)
Parameters
string$
- a string expression.
chars
- the number of characters to return.
Notes
The function returns a String data type. If chars is greater than the number of characters in the string, then the whole string is returned.
Example
This example shows the use of the Left
and Right
string functions.
Sub Main () myString = "Hello out there" MsgBox Left(myString, 5) ' Returns "Hello" MsgBox Mid(myString, 7, 3) ' Returns "out" MsgBox Right(myString, 5) ' Returns "there" End Sub
Mid
Description
Returns a substring within a string.
Syntax
Mid(String$, StartPos, NumChar)
Parameters
String$
- a string expression.
StartPos
- a numeric expression that gives the start position within Str$
for the return substring. StartPos
is the number of characters from the start of Str$
.
NumChar
- a numeric expression that represents the number of characters to return.
Notes
The function returns a String data type. If StartPos
is greater than the length of String$
, a null string is returned. If NumChar
extends beyond the end of String$
, all characters from StartPos
to the end of String$
are returned.
Example
This example shows the use of the Left
and Right
string functions.
Sub Main () myString = "Hello out there" MsgBox Left(myString, 5) ' Returns "Hello" MsgBox Mid(myString, 7, 3) ' Returns "out" MsgBox Right(myString, 5) ' Returns "there" End Sub
Right
Description
Returns a number of characters from the end of the string parameter.
Syntax
Right(string$, chars )
Parameters
string$
- a string or string expression.
chars
- an integer expression defining the number of characters to return.
Notes
The function returns a String data type which is the right-most chars characters of string$
. If chars is greater than the length of string$
, then the return value is string$
.
Example
This example shows the use of the Left
and Right
string functions.
Sub Main () myString = "Hello out there" MsgBox Left(myString, 5) ' Returns "Hello" MsgBox Mid(myString, 7, 3) ' Returns "out" MsgBox Right(myString, 5) ' Returns "there" End Sub
Str
Description
Returns the value of a numeric expression as a string.
Syntax
Str(number)
Parameters
number
- a number or numeric expression.
Notes
The function returns a String data type.
Example
The following example determines the position of a particular digit in a number by converting the number to a string and then using the InStr
search function.
Sub main () Dim a As Long Dim x As Integer Dim aStr As String a = 16374859 aStr = Str(a) ' Convert a to a string. x = InStr(1, aStr, "7") ' Search for a particular digit. MsgBox "7 is digit number " & x & " in " & aStr End Sub
Trim, LTrim, RTrim
Description
LTrim, RTrim and Trim
all return a copy of a string with leading, trailing or both leading and trailing spaces removed.
Syntax
[L | R]Trim (String$ )
Parameters
String$
- a string or string expression.
Notes
Ltrim
removes leading spaces. Rtrim
removes trailing spaces. Trim
removes leading and trailing spaces. All functions return a String data type.
Example
This example uses the LTrim
and RTrim
functions to strip leading and trailing spaces, respectively, from a string variable. It also uses the Trim
function alone to strip both types of spaces.
Sub Main MyString = " <-Trim-> " ' Initialize string. TrimString = LTrim(MyString) MsgBox "\|" & TrimString & "\|" TrimString = RTrim(MyString) MsgBox "\|" & TrimString & "\|" TrimString = LTrim(RTrim(MyString)) MsgBox "\|" & TrimString & "\|" ' Using the Trim function alone achieves the same result ' as the previous statement. TrimString = Trim(MyString) MsgBox "\|" & TrimString & "\|" End Sub
UCase
Description
Returns a string in which all letters of the string$ parameter have been converted to upper case.
Syntax
UCase(string$)
Parameters
string$ - a string expression.
Notes
The function returns a String data type.
Enable Basic Extensions
AltKeyDown
Description
Returns a value that indicates the state of the ALT key.
Syntax
AltKeyDown
Parameters
This function takes no parameters.
Notes
The function returns 1 if the ALT key is down, otherwise it returns 0. Use the CBool
function to convert the return value to a TRUE or FALSE.
ConfirmNoYes
Description
Displays a message dialog with a YES button and NO button. The title of the message box is "Confirm".
Syntax
ConfirmNoYes Message$, IntVar
Parameters
Message$
- a string expression to be used as the displayed message.
IntVar
- a valid integer variable name which is used to store the value of the key pressed.
Notes
When the user exists the message box, the variable IntVar
is set to 1 if the YES button was clicked, or 0 if the NO button was clicked.
The variable IntVar
must be declared as an Integer data type before calling the function.
Example
The following example displays an Altium Designer confirmation dialog. If the user clicks the YES button, a message is displayed.
Sub Main Dim myVal As Integer ConfirmNoYes "Do you want to display a message?", myVal If myVal = 1 Then ' If the user presses YES MsgBox "You pressed the YES button" End If End Sub
ConfirmNoYesCancel
Description
Displays a message dialog with a YES button, NO button, CANCEL button and question mark icon.
Syntax
ConfirmNoYesCancel Message$, IntVar
Parameters
Message$
- a string expression to be used as the displayed message.
IntVar
- a valid integer variable name which is used to store the value of the key pressed.
Notes
When the user exits the message box, the variable IntVar
is set to 6 if the YES button was clicked, 7 if the NO button was clicked, or 2 if the CANCEL button was clicked.
The variable IntVar
must be declared as an Integer data type before calling the function.
Example
The following example displays an Altium Designer confirmation dialog and displays a message if the YES or NO buttons are pressed.
Sub Main Dim myVal As Integer ConfirmNoYesCancel "Click YES or NO to display a message?", myVal Select Case myVal Case 6 ' YES button pressed MsgBox "You pressed the YES button" Case 7 ' NO button pressed MsgBox "You pressed the NO button" End Select End Sub
GetCurrentWindowHandle
Description
Returns an integer representing the system ID handle of the currently active window.
Syntax
GetCurrentWindowHandle IntVar
Parameters
IntVar a previously declared variable of Integer data type in which to store the ID handle.
Notes
Whenever the Windows operating system creates a display window, it creates a unique ID number for the window. This extension allows you to determine the Windows ID number for the active window.
The number returned by this extension is not used directly by any other Enable Basic function, procedure or extension. It may be useful, however, if you are declaring functions within the Windows system DLLs for use with your macro.
ResetCursor
Description
Changes the cursor to the default arrow cursor.
Syntax
ResetCursor
Parameters
This extension takes no parameters.
RunApplication
Description
Runs an application program.
Syntax
RunApplication AppName$
Parameters
AppName$
- a string expression containing the name and path of an executable program file.
Notes
This extension uses the RunApplication
process to run an executable file. This extension has the same function as the Shell
procedure.
Example
This example runs the Notepad application.
Sub Main RunApplication "NOTEPAD.EXE" End Sub
SetCursorBusy
Description
Changes the cursor to the default busy cursor.
Syntax
SetCursorBusy
Parameters
This extension takes no parameters
Notes
Use ResetCursor
to reset the cursor to its default arrow icon.
ShiftKeyDown
Description
Returns a value that indicates the state of the SHIFT key.
Syntax
ShiftKeyDown
Parameters
None
Notes
The function returns 1 if the SHIFT key is down, otherwise it returns 0. Use the CBool function to convert the return value to a TRUE or FALSE.
ShowError
Description
Displays a warning dialog containing an OK button and the warning icon.
Syntax
ShowError Message$
Parameters
Message$
- a string expression containing the message to display in the warning box.
Notes
This extension displays a warning message. It does not cause an error to be generated.
This extension is identical to the ShowWarning
extension.
ShowInfo
Description
Displays an information dialog containing an OK button and the information icon.
Syntax
ShowInfo Message$
Parameters
Message$
- a string expression containing the message to display in the information box.
ShowWarning
Description
Displays a warning dialog containing an OK button and the warning icon.
Syntax
ShowWarning Message$
Parameters
Message$
- a string expression containing the message to display in the warning box.
Notes
This extension is identical to the ShowError
extension.