ProgrammerGuide.Net | Step by Step Programmer Guide

VB-File Folder

File Folder,

Dir
Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

Syntax
Dir[(pathname[, attributes])]

The Dir function syntax has these parts:

PartDescription
pathnameOptional. String expression that specifies a file name — may include directory or folder, and drive. A zero-length string (“”) is returned if pathname is not found.
attributesOptional. Constant or numeric expression, whose sum specifies file attributes. If omitted, returns files that match pathname but have no attributes.

Settings
The attributes argument settings are:

Constant ValueDescription
vbNormal 0(Default) Specifies files with no attributes.
vbReadOnly  1Specifies read-only files in addition to files with no attributes.
vbHidden2Specifies Hidden files in addition to files with no attributes.
VbSystem4Specifies System files in addition to files with no attributes Not Available on the Macintosh..
vbVolume 8Specifies volume label; if any other attributed is specified, vbVolume is ignored. not available on the Macintosh.
vbDirectory16Specifies directories or folders in addition to files with attributes.
vbAlias64Specified file name is an alias. Available only on the Macintosh.


Note These constants are specified by Visual Basic for Applications and can be used anywhere in your code in place of the actual values.

Example:
If Dir(“c:\windows\win.ini”) = “win.ini” Then
MsgBox “File exists”
Else
MsgBox “File does not exist”
End If

ChDir
Changes the current directory or folder.

Syntax
ChDir path

The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.

Remarks
The ChDir statement changes the default directory but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive.

Example:
Dim Path as string
Dir(“C:\NewFolder”) = Path
Path = ChDir(“C:\MyFolder”

ChDrive
Changes the current drive.
Syntax
ChDrive drive

The required drive argument is a string expression that specifies an existing drive. If you supply a zero-length string (“”), the current drive doesn’t change. If the drive argument is a multiple-character string, ChDrive uses only the first letter.

Example:
ChDrive “D” ‘ Make “D” the current drive.

CurDir
Returns a Variant (String) representing the current path.

Syntax
CurDir[(drive)]

The optional drive argument is a string expression that specifies an existing drive. If no drive is specified or if drive is a zero-length string (“”), CurDir returns the path for the current drive. On the Macintosh, CurDir ignores any drive specified and simply returns the path for the current drive.

Example:
‘ Assume current path on C drive is “C:\WINDOWS\SYSTEM” (on Microsoft Windows).
‘ Assume current path on D drive is “D:\EXCEL”.
‘ Assume C is the current drive.
Dim MyPath
MyPath = CurDir ‘ Returns “C:\WINDOWS\SYSTEM”.
MyPath = CurDir(“C”) ‘ Returns “C:\WINDOWS\SYSTEM”.
MyPath = CurDir(“D”) ‘ Returns “D:\EXCEL”.

MkDir
Creates a new directory or folder.
Syntax
MkDir path

The required path argument is a string expression that identifies the directory or folder to be created. The path may include the drive. If no drive is specified, MkDir creates the new directory or folder on the current drive.

Example:
‘Creates a folder called ‘New Folder’
MkDir “C:\New Folder”

RmDir Function
Removes an existing directory or folder.
Syntax
RmDir path

The required path argument is a string expression that identifies the directory or folder to be removed. The path may include the drive. If no drive is specified, RmDir removes the directory or folder on the current drive.

Remarks
An error occurs if you try to use RmDir on a directory or folder containing files. Use the Kill statement to delete all files before attempting to remove a directory or folder.

Example:
RmDir “c:\windows\pictures”

Kill Function
Deletes files from a disk.
Syntax
Kill pathname
The required pathname argument is a string expression that specifies one or more file names to be deleted. The pathname may include the directory or folder, and the drive.

Example:
Kill “c:\Blah.txt”

FileDateTime
Returns a Variant (Date) that indicates the date and time when a file was created or last modified.
Syntax
FileDateTime(pathname)

The required pathname argument is a string expression that specifies a file name. The pathname may include the directory or folder, and the drive.

Example:
Dim MyStamp
‘ Assume TESTFILE was last modified on September 2, 2005 at 4:00:00 PM.
MyStamp = FileDateTime “c:\Blah.txt” ‘ Returns “2/9/05 4:00:00 PM”.

FileLen
Returns a Long specifying the length of a file in bytes.
Syntax
FileLen(pathname)

The required pathname argument is a string expression that specifies a file. The pathname may include the directory or folder, and the drive.
Remarks
If the specified file is open when the FileLen function is called, the value returned represents the size of the file immediately before it was opened.
Note To obtain the length of an open file, use the LOF function.

Example:
Dim Size
Size = FileLen(“TESTFILE”) ‘ Returns file length (bytes).

FileCopy
Copies a file.
Syntax
FileCopy source, destination

PartDescription
sourceRequired. String expression that specifies the name of the file to be copied. The source  may include directory or folder, and drive.
destinationRequired. String expression that specifies the name of the file to be copied. The destination may include directory or folder, and drive.

Remarks
If you try to use the FileCopy statement on a currently open file, an error occurs.

Cut, Copy & Pasting Text
The Clipboard object represents the Windows clipboard which is available to all running applications, therefore you can allow your users to place text or pictures on the Clipboard and paste them anywhere they like. Setting up menu items for cut, copy, and pasting from and into one TextBox is fairly simple.

Example:
Private Sub mnuCopy_Click( )
Clipboard.Clear
Clipboard.SetText txtMain.SelText
End Sub
Private Sub mnuCut_Click( )
Clipboard.Clear
Clipboard.SetText txtMain.SelText
txtMain.SelText = “”
End Sub
Private Sub mnuPaste_Click( )
txtMain.SelText = Clipboard.GetText
End Sub

GetAttr
Returns an Integer representing the attributes of a file, directory, or folder.

Syntax
GetAttr(pathname)

The required pathname argument is a string expression that specifies a file name. The pathname may include the directory or folder, and the drive.

Return Values
The value returned by GetAttr is the sum of the following attribute values:

ConstantValueDescription
vbNormal0Normal
vbReadOnly1Read-only.
vbHidden2Hidden
vbSystem4System file. Not available on the Macintosh.s
vbDirectory16Directory or folder.
vbArchive32File has changed since last backup. Not available on the Macintosh.
vbAlias64Specified file name is an alias. Available only on the Macintosh.

Note:
These constants are specified by Visual Basic for Applications. The names can be used anywhere in your code in place of the actual values.

SetAttr
Sets attribute information for a file.

Syntax
SetAttr pathname, attributes
The SetAttr statement syntax has these named arguments:

PartDescription
pathname Required. String expression that specifies a file name — may include directory or folder, and drive.
attributesRequired. Constant or numeric expression, whose sum specifies file attributes.

Settings
The attributes argument settings are:

ConstantValueDescription
vbNormal0Normal
vbReadOnly1Read-only.
vbHidden2Hidden
vbSystem4System file. Not available on the Macintosh.s
vbArchive32File has changed since last backup. Not available on the Macintosh.
vbAlias64Specified file name is an alias. Available only on the Macintosh.

FreeFile function
Returns an Integer representing the next file number available for use by the Open statement.

Syntax
FreeFile[(rangenumber)]
The optional rangenumber argument is a Variant that specifies the range from which the next free file number is to be returned. Specify a 0 (default) to return a file number in the range 1 – 255, inclusive. Specify a 1 to return a file number in the range 256 – 511.

Remarks
Use FreeFile to supply a file number that is not already in use.

Example:
Dim MyIndex, FileNumber
For MyIndex = 1 To 5 ‘ Loop 5 times.
FileNumber = FreeFile ‘ Get unused file number.
Open “TEST” & MyIndex For Output As #FileNumber ‘ Create file name.
Write #FileNumber, “This is a sample.” ‘ Output text.
Close #FileNumber ‘ Close file.
Next MyIndex

Open Function
Enables input/output (I/O) to a file.

Syntax
Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

The Open statement syntax has these parts:

Part Description
pathnameRequired. String expression that specifies a file name — may include directory or folder,  and drive.
modeRequired. Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.
accessOptional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write
lock Optional.Keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.
filenumberRequired. A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to Obtain the next available file number.
reclengthOptional. Number less than or equal to 32,767 (bytes). For files opened for random ,  Access this value is the record length. For sequential files, this value is the number of characters buffered.

Remarks
Output: use the print statement to print something in a file. Input: use this to open and read a file. Append: use this to write something into the file but keep what is already in the file. Binary: use this for binary access files Random: use this for random access files. You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer. If the file specified by pathname doesn’t exist, it is created when a file is opened for Append, Binary, Output, or Random modes. If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs. The Len clause is ignored if mode is Binary. Important In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.

Example:
Open “a:\gordon.txt” For Output As #1
Print #1, Text1.Text ‘prints Text1 into the file
Close #1

Close Statement
Concludes input/output (I/O) to a file opened using the Open statement.
Syntax
Close [filenumberlist]
The optional filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number : [[#]filenumber] [, [#]filenumber] . . .

Remarks
If you omit filenumberlist, all active files opened by the Open statement are closed. When you close files that were opened for Output or Append, the final buffer of output is written to the operating system buffer for that file. All buffer space associated with the closed file is released. When the Close statement is executed, the association of a file with its file number ends.

Line Input
Reads a single line from an open sequential file and assigns it to a String variable.
Syntax
Line Input #filenumber, varname
The Line Input # statement syntax has these parts:

PartDescription
filenumberRequired. Any valid file number.
varnameRequired. Valid Variant or String variable name.

Remarks
Data read with Line Input # is usually written from a file with Print #.

Example:
Open “a:\gordon.txt” For Input As #1
Line Input #1, TextLine ‘ Read line into variable.
Close #1

EOF Function
Returns an Integer containing the Boolean value True when the end of a file opened for Random or sequential Input has been reached.
Syntax
EOF(filenumber)
The required filenumber argument is an Integer containing any valid file number.
Remarks
Use EOF to avoid the error generated by attempting to get input past the end of a file. The EOF function returns False until the end of the file has been reached. With files opened for Random or Binary access, EOF returns False until the last executed Get statement is unable to read an entire record. With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using the EOF function. With files opened for Output, EOF always returns True.

Example:
dim templine as string
Open “a:\ratbag.txt” For Input As 1
Do Until EOF(1)
Line Input #1, templine
Text1.Text = text1.text + templine
Loop
Close #1

If errornumber is defined, the Error statement calls the error handler after the properties of Err object are
assigned the following default values:

The Resume statement syntax can have any of the following forms:

PropertyValue
NumberValue specified as argument to Error statement. Can be any valid error number.
SourceName of the current Visual Basic project.
DescriptionString expression corresponding to the return value of the Error function for the specified Number, if this string exists. If the string doesn’t exist, Description contains.
HelpFileThe fully qualified drive, path, and file name of the appropriate Visual Basic Help file.
LastDLLErrorZero.

Example:
On Error Resume Next ‘ Defer error handling.
Error 11 ‘ Simulate the “Division by zero” error.

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?