Sunday, November 21, 2010
Visual Basic Forms Method : Hide
Purpose : The Hide method makes an active and visible form disappear from the screen and is the same as setting the form's visible property to False ( 0 ) .
Syntax :
[ form . ] Hind
Private Sub Form1_Load ( )
Form2.Hide
Form2.BackColor = RGM ( 0 , 255 , 0 )
Form2.ForeColor = RGB ( 0 , 0 , 255 )
MsgBox " Press OK to see form2 "
Form2.Show
End Sub
The Hide method reduces clutter by removing a form from the screen without removing it from memory . Any forms not initially needed can be loaded and hidden until desired. The Show method displays a hidden form onscreen. Hidden forms take a little more time to load at program startup but can then be displayed very quickly.
Show Method :
The Hide method shares an inverse relationship with the Show method. Hide removes the form from sight and show restores it. In the sample syntax , the two methods work together to make a form invisible while its color change.This technique also can be used for a warning bialog box that displays context-sensitive messages. if the form is not loaded , the show method loads it into memory.
Visible Property :
When the Hide method makes a form invisible , the Visible property of the form becomes False. The difference between using the Hide method and directly changing the setting of the visible property lies in the types of objects affected . the hide method can only be used on a form .In contrast , the visible property can be used on any of the objects in visual basic.
Saturday, November 20, 2010
Visual Basic Forms Property : ControlBox
Purpose : The ControlBox property governs whether a control box appears in the top-right corner of a form. This property is read -only at runtime.
Syntax :
[ form . ] ControlBox
Argument of the ControlBox Property
form : Name property of the form ( if no name is specified, references the current form's controlbox property )
Public Sub SetColor ( FormName As Form )
If FormName.ControlBox = 0 Then
FormName.BackColor = RGB ( 192, 192 192 )
Else
FormName.BackColor = RGB ( 0 , 128 , 0 )
End If
End Sub
Visual Basic Forms Property : AutoShowChildren
Syntax :
Name.AutoShowChildren [ = Boolean% ]
Arguments of the AutoShowChildren Property
Argument : Description
boolean% : An optional Boolean expression that specifies whether MDI child forms are automatically visible. if not included defaults to True.
Name : Name property of MDIForm
Private Sub Form_Load
MDIForm1.AutoShowChildren = True
End Sub
Visual Basic Forms Method : Arrange
Syntax :
[ Name ] . Arrange Setting%
Arguments of the Arrange Method
Arguments : Decsription
Name : Name property of the MDI form
setting% : A value that specifies how to arrange the windows or icons
Private Sub menuWindow_Click ( Index As Integer )
Select Case Index
Case 0 : MDIForm.Arrange vbCascade
Case 1 : MDIForm.Arrange vbTileHorizontal
Case 2 : MDIForm.Arrange vbTitleVertical
Case 3 : MDIForm.Arrange vbArrangeIcons
End Select
End Sub
Visual Basic Forms Event : Activate
Syntax :
Sub Form_Activate ( )
Sub MDIForm_Activate ( )
Sub DataReport_Activate ( )
An object can become active by a user action such as clicking the object or by using the Show or SetFocus method in code. The activate event can occur only when an object is visible . A form loaded with the Load statement , for example , isn't visible unless you use the Show method or set the form's Visible property to True. The Activate event occurs only when moving the focus within an application. Moving the focus to or from an object in another application doesn't trigger the event.
The Deactivate Event :
the Deactivate and Activate events have an inverse relationship. Whereas the Activate eent occurs when a form becomes active , the Deactivate event occurs when a form is no longer active. The Deactivate event occurs only when moving the focus within an application. Moving the focus to or from an object in another application doesn't trigger either event. The Deactivate event doesn't occur when unloading an object.
The LostFocus event occurs before the Deactivate event.
Wednesday, November 3, 2010
Visual Basic Operating Environment Function : Shell
Syntax :
Shell ( program-name$ [ , mode% ] )
A% = Shell ( " WINWORD.EXE " )
B% = Shell ( " C : \ WORD \ WINWORD.EXE " , 3 )
The Shell function loads an executable file into the windows environment and returns the task ID number that Windows assigns to each tunning program.
the first example loads and runs the program file WINWORD.EXE . it assumes that the file is in the default directory or in a directory specified by the path statement. because the mode is not specified , it uses the default mode of 2 ( minimized with focus )
Shell function constants of then mode% parameter
consant : value : Description
vbHide : 0 : Hides window with focus
vbNormalFocus : 1 : give window focus and restores ti to its original size and position.
vbMinimizedFocus : 2 : Minimizes and gives window focus
vbMaximizedFocus : 3 : Mazimizes and gives window focus
vbNormalNoFocus : 4 : Restores window to its original size and position with-out focus
vbMinimizedNoFocus : 6 : Minimizes window without focus.
Visual Basic Operating Environment Function : Environ, Environ$
Syntax :
Environ ( { entry_name$ | entry-position% } )
Environ$ ( { entry_name$ | entry-position% } )
A$ Environ ( " path " )
A$ Environ ( 1 )
DOS maintains a table of values called environment variables. values in the environment table typically store information abut such things as the current drive and path, the location of the command processor, or special settings needed y various programs.
The Environ and Environ$ functions allow the program to read the current setting of the operating system's environment table . Entries in the environment table are set by using the DOS command syntax SET ENTRY_NAME = ENTRY_VALUE. see a DOS reference manual for more information on the SET command. Environ allows you to specify either the name or position of the entry to be retrieved.
Visual Basic Operating Environment Function : Command
Command
Command$
Monday, November 1, 2010
Visual Basic Operating Environment Statement : Beep
Beep
The example beeps the speaker if the variable ErrorNumber is set. The Beep statement causes the computer to send a short tone to the speaker. you can control neither the tone not the duration; however, issuing several beep command consecutively can create the effect of a longer beep.
Visual Basic Operating Environment Statement : AppActivate
AppActivate ProgramTitle$ [, wait]
AppActivate “ paintbrush-( untitled )” , True
The second example works the same as the first example , except that it waits until the calling application has the focus.
Friday, October 22, 2010
Microsoft Excel command - Data Table (Two Variable)
This tutorial assumes that you have read the earlier one and are comfortable with creating a single variable data table.
Create a new excel file as shown in the screenshot above. In cell A5,
enter the formula =B1 * (1 + B2) ^ B3.
As you can see, the $5000 invested at 7.5% for 5 years will give $7,178.15.
A two variable data table gives you results by varying two different variables in the equation. In our case, the equation is that of compound interest i.e.
Formula for calculating compound interest:
A = P * (1 + r/n) ^ nt
Where:
· P = principal amount (initial investment)
· r = annual interest rate (as a decimal)
· n = number of times the interest is compounded per year
· t = number of years
· A = amount after time t
We will be varying the annual interest rate and the number of years to find the varying results.
After you have created the file according to the screenshot above, select the data range A5:F10.
In Excel 2007, go to Data > What-If Analysis > Data Table. In Excel 2003, the menu path is Data > Table or you can use the shortcut key Alt + D + T in this order.
This wills popup a window where you will be asked to enter Row Input Cell and the Column Input Cell. Select the Column Input Cell as $B$2 and the Row Input Cell as$B$3 and hit OK.
The cells will be populated as shown in the screenshot below. As usual, you can choose to format the same currency.
How is it works?
Cells B6:F10 hold the formula {=TABLE(B3,B2)}.
Here, the values B4 to F4 are substituted for B3 in the formula in cell A5 and values A6 to A10 are substituted for B2 in the formula in cell A5 and the results are then populated accordingly.
Hence, for 1 year at 8%, the amount is $5,400, for 3 years at 10%; the amount is $6,655.00 and so on.
Microsoft Excel command - Data Table (Single Variable)
Data Tables is also an advanced topic in Microsoft Excel that falls under the category of What-If Analysis. What-If or Sensitivity Analysis is carried out to study the variation of the output to changes in the input variable.
Consider a case of compound interest, where you invest a certain amount of money in a bank deposit and the amount is compounded every year.
Formula for calculating compound interest:
A = P * (1 + r/n) ^ nt
Where:
· P = principal amount (initial investment)
· r = annual interest rate (as a decimal)
· n = number of times the interest is compounded per year
· t = number of years
· A = amount after time t
Now, if suppose we want to see what the final amount will be at different interests rates, we can quickly use a data table for the same.
Excel Help describes a data table as:
“A data table is a range of cells that shows how changing one or two variables in your formulas (formula: A sequence of values, cell references, names, functions, or operators in a cell that together produce a new value. A formula always begins with an equal sign (=).) will affect the results of those formulas. Data tables provide a shortcut for calculating multiple results in one operation and a way to view and compare the results of all the different variations together on your worksheet. “
Without wasting any more time on descriptions, let’s get down to creating a data table for our compound interest example above.
Open a new excel file and enter the following as given in the screenshot below:
The cell B5 has the formula =B1 * (1 + B2) ^ B3
As you can see, the $5000 invested at 7.5% for 5 years will give $7,178.15.
Now, we will create a data table to see what amount we will receive by changing the interest rate.
Fill cells A6 to A10 with different interest rates. I've filled it with values from 6% to 10%. Now, select the cells A5:B10.
In Excel 2007, go to Data > What-If Analysis > Data Table. In Excel 2003, the menu path is Data > Table or you can use the shortcut key Alt + D + T in this order.
This wills popup a window where you will be asked to enter Row Input Cell and the Column Input Cell. Select the Column Input Cell as $B$2 and leave the Row Input Cell blank and hit OK.
The values will be filled in as shown below. You can choose to format them as currency, but that I have left it up to you.
How is it Works?
Well, we did get the results, but the question remains on what just happened.
To understand this simply, the Column Input Cell is the variable whose value we are going to vary. If supposing the data was presented horizontally instead of vertically which is our case, then you would need to select it as a Row Input Cell.
The values in cells A6 to A10 are then passed to the formula in cell B5 and the corresponding results are populated in cells B6 to B10.
If you look at cells B6 to B10, they contain the formula {=TABLE(,B2)}
Can you try creating a Data Table using a Row Input Cell? Why don't you post your solution below or on your blog and post a link below in the comments area.
Wednesday, October 13, 2010
Visual Basic File System : FileSystemObject
The FileSystemObject object allows you to work with drives, folders and files programmatically just as you can in the windows explorer interactively. you can copy, move and create file and folder; get information about the drives , folders and files; and so on. FileSystemObject gives you direct access to the windows explorer functionality with better performance than the standard file system access in visual basic and see the object list.
Drive : Gathers information about drives attached to the system, such as how much room is available.
Folder : Creates , deletes , or moves folders , plus queries the system as to their names pates and so on.
Files : Creates , deletes or moves files , pluse queries the system as to their names, paths and so on.
FileSystemObject : Creates, deletes , gains information about and generally manipulates drives folders and files . this is he main object of the group.
TextStream : Reads and writes text files.
- Use the create object method, or dimension a variable as a File System object object to create a File system object object
- Use to appropriate method on the newly created object.
- Access the object’s properties.
Dim fso As New FileSystemObject
Set fso = CreateObject ( “ Scripting.FileSystemObject “ )
- Total size of the drive in bytes ( TotalSize property )
- How much space is available on the drive in bytes ( AvailableSpace and FreeSpace properties )
- What letter is assigned to the drive ( DriveLetter property )
- What type of drive it is, such as removable, fixed, network, CD-ROM, or RAM disk ( DriveType property )
- Drive’s serial number ( SerialNumber property )
- Type of file system the drive use, such as FAT, FAT32, NTFS and so on ( FileSystem property )
- Whether a drive is available for use (IsReady property)
- Name of the share and /or volume ( ShareName and VolumeName properties )
- Path or root folder of the drive (path and RootFolder properties)
Private Sub Command1_Click()
Dim fso As New FileSystemObject, drv As Drive, s As String
Dim t As String
Set drv = fso.GetDrive(fso.GetDriveName ( " c : " ) )
s = "Drive " & drv.DriveLetter & " . "
s = s & "Total Space : " & FormatNumber(drv.TotalSize / 1024, 0 )
s = s & " kb " & vbCrLf
s = s & drv.VolumeName & vbCrLf
s = s & " Free Space : " & FormatNumber(drv.FreeSpace / 1024, 0 )
s = s & " kb " & vbCrLf
'
Select Case drv.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
'
s = s & t & " Drive " & vbCrLf
s = s & drv.SerialNumber & vbCrLf
s = s & drv.FileSystem & vbCrLf
s = s & drv.Path & vbCrLf
s = s & drv.RootFolder & vbCrLf
MsgBox s
End Sub
-Create a folder : FileSystemObject.CreateFolder
-Delete a folder : Folder.Delete or FileSystemObject.DeleteFolder
-Move a folder : Folder.Move or FileSystemObject.MoveFolder
-Copy a folder : Folder.Copy or FileSystemObject.CopyFolder
-Retrieve the name of a folder : Folder.Name
-Find out whether a folder exists on a drive : FileSystemObject.FolderExists
-Get an instance of an existing folder object : FileSystemObject.GetFolder
-Find out the name of a folder’s parent folder : FileSystemObject.GetParentFolderName
-Fin
'Project>References>Microsoft Scripting Runtime
Private Sub Command1_Click()
Dim fso As New FileSystemObject, fldr As Folder, s As String
Set fldr = fso.GetFolder ( " c:\a\b " )
Debug.Print "Folder Name : " & fldr.Name
Debug.Print "Contained on drive : " & fldr.Drive
If fldr.IsRootFolder = True Then
Debug.Print " This folder is a root folder"
Else
Debug.Print " This folder isn't a root folder "
End If
Debug.Print fldr.ParentFolder
Debug.Print fldr.Path
Debug.Print FormatNumber(fldr.Size / 1024, 0) & " KB "
Debug.Print fldr.DateCreated & " Folder Created Date "
Debug.Print fldr.DateLastModified & " Folder Last Modified Date "
Debug.Print fldr.DateLastAccessed & " Folder Last Accessed Date "
End Sub
Private Sub Command2_Click()
Dim fso As New FileSystemObject
fso.CreateFolder ( " c:\1 " )
Debug.Print "Basename = " & fso.GetBaseName( " c:\1 " )
fso.DeleteFolder ( " c:\1 " )
End Sub
- Creating adding, or removing data; and reading files
- Moving, copying and deleting
Microsoft Excel command - Goal Seek
- From the Excel menu bar, click on Tools
- From the drop down menu, click on Goal Seek
- A dialogue box pops up like the one below
Monday, October 11, 2010
Visual Basic File System Statement : SetAttr
SetAttr filename$ , attrbuteBits%
All file , directories and volumes have an attribute byte associated with then. This information indicates whether the filename is normal, read-only, hidden, system a volume label, a directory, or has been modified since the last backup.
Constant : Value : Description
vbNormal : 0 : Normal
vbReadOnly : 1 : Read-Only
vbHidden : 2 : Hidden
vbSystem : 4 : System file
vbDirectory : 16 : Directory
vbArchive : 32 : File has changed since last backup
Visual Basic File System Statement : RMDir
RmDir dirname$
dirname$ must be in the format of
[ dirve: ] [\] dir [ \ subdir ] [\ subdir ] .......
RmDir "\TEST"
RmDir "D:\TEST"
Visual Basic File System Statement : Name
Name oldname As newname
in the example changes the name of the file Test_1.Date in the default directory to Test_2.Dat.
Visual Basic File System Statement : MKDir
MKDir dirname$
dirname$ must be in format of
[drive:][ \ ] dir [ \ subdir ] [ \ subdir ] ...
MKDir "\TEST"
MKDir "D:\TEST"
the first example creates the subdirectory TEST below the defult directory on the default drive.
the second line creates the subdirectory TEST below the root directory of the default drive.
and third example creates the subdirectory TEST below the root directory of the D drive.
Visual Basic File System Statement : Kill
Kill filename$
in this example erases the file that is currently selected in the FileListBox named File1.
Visual Basic File System Function : GetAttr
GetAttr ( fileName$ )
Constant : Value : Description
vbNormal : 0 : Normal
vbReadOnly : 1 : Read-Only
vbHidden : 2 : Hidden
vbSystem : 4 : System file
vbDirectory : 16 : Directory
vbArchive : 32 : File has changed since last backup
Visual Basic File System Function : FileLen
FileLen ( filename$ )
It return a long integer indicating the total number of bytes in the file.
Visual Basic File System Function : FileDateTime
FileDateTime ( filename$
Usethe FileDateTime function to datermine when a DOS file was created or last saved. The function returns a date.
Visual Basic File System Statement : FileCopy
FileCopy source$ , dest$
This command copies a xopies a DOS file. the source$ file can be opened for read-only access but must not be opened for write access. You can specify a drive and directory in either of the filenames, but you cannot specify any wildcards. The sample syntax copies the file TEMP.TEM to the filename specifed by the variable dataFileName
Visual Basic File System Function : Dir, Dir$
For the first call to Dir
Dir [ ( pattern$ [ , Attributes ] ) ]
For each successive call for the same pattern :
Dir
Do Until Temp$ = ""
i=i+1
Docs ( i ) = Temp$
Temp$ = Dir
Loop
Temp$ = Dir ( "*.*" , vbHidden )
Temp$ = Dir ( "c:\ " , vbDirectory )
Constant : Value : Description
vbNormal : 0 : Normal
vbHidden : 2 : Hidden
vbSystem : 4 : System file
vbVolume : 8 : Volume label;
vbDirectory : 16 : Directory
Sunday, October 10, 2010
Visual Basic File System Function : CurDir, CurDir$
CurDir [ ( drive$ ) ]
CurDir$ [ ( drive$ ) ]
A$ = CurDir ( " C " )
CDirectory = CurDir ( " C: " )
Visual Basic File System Statement : ChDriver
ChDrive Drive$
ChDirive "C:"
Visual Basic File System Statement : ChDir
ChDir path$
path$ must be a string in the format of
[drive:] [\] dir [\subdir] [\subdir...]
ChDir "\MAIN\MAILBOX"
ChDir "\\MySERVER\MAIN\MAILBOX"
The ChDir statement can affect the operation of file -related commands
Path$ is not longer then 128 characters
Wednesday, October 6, 2010
Visual Basic Date and Time Function : TimeValue
timeValure ( timestring$ )
timestring$ : Text string to convert that is an acceptable time value
Examples of valid timeString value
timestring$
3:05
3:05:23
03:05:23
15:05
3:05 AM
October 6, 2010 3:05 am
Private Sub Command1_Click()
Dim EndTime, FirstTime, T
Dim Seconds$
Start:
On Error GoTo NotTime
If Text1.Text = "" Or Text2.Text = "" Then
MsgBox "Please Enter a tim in each box."
Exit Sub
End If
FirstTime = TimeValue(Text1.Text)
EndTime = TimeValue(Text2.Text)
Text1.Text = Str$(FirstTime)
Text2.Text = Str$(EndTime)
T = EndTime - FirstTime
Seconds$ = Str$(Int(T * 86400))
Label1.Caption = Seconds$ + " seconds "
Exit Sub
NotTime:
MsgBox "Please Enter a value Time."
Text1.Text = ""
Text2.Text = ""
Resume Start
End Sub
Tuesday, October 5, 2010
Visual Basic Date and Time Function : TimeSerial
TimeSerial ( hour% , minute% , second% )
hour% : A number or expression that evaluates to a number between 0 and 23 inclusive
minute% : A number or expression that evaluates to a number between 0 and 59 inclusive
second% : A number or expression that evaluates to a number between 0 and 59 inclusive
Visual Basic Date and Time Event : Timer
Sub Name_Timer ( [ Index As Integer ] )
Name : Name property of the timer
Index : Serves as a reference for the part of a control array
Dim x%, y%, Radius%
Const pi = 3.14159265
Private Sub Timer1_Timer()
Cls
Static num As Double
FillColor = QBColor(1)
FillStyle = 1
x% = ScaleWidth / 2
y% = ScaleHeight / 2
Radius% = ScaleWidth / 4
Circle (x%, y%), Radius%, num, -6.283
num = num - ((2 * pi) / 60)
Text1.Text = Str$(num)
If Abs(num) >= 6.238 Then
num = 0
Timer1.Enabled = 0
Cls
End If
End Sub
Monday, October 4, 2010
Visual Basic Date and Time Statement : Time , Time$
Time = expression$
Time$ = timestring$
timestring$ : Time in string format hh:mm:ss
expression$ : Acceptable time format ( more general than timestring$ )
timestring$ : Value
hh : A number between 00 and 23 inclusive
mm : A number between 00 and 59 inclusive
ss : A number between 00 and 59 inclusive
expression$
2:21
2:21 PM
14:21
October 4, 2010 10:11 am