Three of the four operating method of Excel-VBA file

Third, the use FileSystemObject object to handle the file

FileSystemObject object model that is provided by Microsoft specifically designed to access the computer's file system, with a large number of properties, methods and events. Its object-oriented "object.method" syntax to handle folders and files, very convenient to use (needs Office 2000 or later). FileSystemObject is not part of VBA, which is in the form of a COM component provides. Therefore, to use first create a FileSystemObject object.

FileSystemObject object model contains the following objects and collections:

· FileSystemObject main object containing to create, delete and obtain information, as well as for operating methods and properties drives, folders and files.

· Drive object containing methods and properties for obtaining information, the information about the connection on the system drive, if the number of available space. Not necessarily a hard disk drive, can also be a CD-ROM, U disk and even connect logically through the network hard disk (such as a company in the sector shared server network drives).

· Drives set, provides a list of drives, these drives are connected to the physical or logical system. Drives collection includes all drives, regardless of the type.

· File object containing to create, delete or move files of methods and properties.

· Files collection, provides a list of all the files contained in the folder.

· Folder object that contains used to create, delete, or move methods and properties of the folder.

· Folders collection, provides a list of all the folders contained within the folder of.

· TextStream object that is used to read and write text files.


(A) preparation

To use the FileSystemObject object, first create it. Create a FileSystemObject object to use CreatObject function. CreateObject function to create and return a reference to the ActiveX object.

Syntax: CreateObject (class, [servername] )
application name and type class is to be created. 
servername To create a network server object's name on it. (If you want to create an object on a remote computer before using)

class parameters appname.objecttype this syntax, comprising the following parts:

appname necessary; providing the name of the application object. 
objecttype required; to be created object types or classes.

Therefore, we use the following code to create a FileSystemObject object:

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

Scripting is the name of a type library, the name of the object FileSystemObject is to be created.

Similarly, we can create a Dictionary object as follows:
Dim d
the Set d = CreateObject ( "Scripting.Dictionary")


Method (b) subject the FileSystemObject

FileSystemObject object model, some functions are duplicated, as CpoyFile methods available FileSystemObject object, the method can also be used Copy File object to copy files. Here we introduce the way the FileSystemObject object.

1, GetDrive way

Syntax: object.GetDrive drivespec

drivespec parameter may be a drive letter (c), a drive letter followed by a colon (c :), a drive letter followed by a colon and path separator (c: \) or any description network share ( \\ Computer2 \ share1 ).

Action: Returns a Drive object corresponding to the specified path in the drive.

Example:
Dim d
the Set d = fso.GetDrive ( "D:") 'variable d represents the drive D objects
, if any drivespec does not meet an acceptable form or does not exist, an error occurs.

Note: For simplicity, assume the example fso is already created FileSystemObject object

2, GetDriveName method

Syntax: object.GetDriveName (path)

Action: Returns a string that contains the name of the specified path of the drive.

Example:
the Debug.Print fso.GetDriveName ( "C: \ test.txt") 'Now window "c:"

3, GetExtensionName 方法

Syntax: object.GetExtensionName (path)

Action: Returns a string member last extension path contains.

Example:
the Debug.Print fso.GetExtensionName ( "C: \ test.txt") 'Now window "txt"

4, GetBaseName method

Syntax: object.GetBaseName (path)

Action: Return the name of substantially (minus any file extension) of a string containing the last path member.

Example:
the Debug.Print fso.GetBaseName ( "C: \ ABC \ test.txt") 'Now window "test"

5、GetAbsolutePathName 方法

Syntax: object.GetAbsolutePathName (pathspec)

Role: Returns the path to provide a complete description, a clear path.

Example:
If pathspec empty string "", the current return path. Suppose the current path is C: \ Documents and Settings \ yc \ My Documents

Debug.Print fs.GetAbsolutePathName("")  '显示C:\Documents and Settings\yc\My Documents

Debug.Print fs.GetAbsolutePathName ( "c: ..") 'Display C: \ Documents and Settings \ yc, i.e., parent directory

Debug.Print fs.GetAbsolutePathName("abc") '显示C:\Documents and Settings\yc\My Documents\abc

Debug.Print fs.GetAbsolutePathName("c:\test.txt") '显示C:\test.txt

6, GetFile method

Syntax: object.GetFile (filespec)

Role: Returns a specified path and file corresponding File object.

Example:
Dim f
the Set f = fso.GetFile ( "c: \ test.txt") 'variable f represents the target file test.txt
Note: If the specified file does not exist, an error occurs.

7, GetFileName method

Syntax: object.GetFileName (pathspec)

Action: Returns the last element in the path, the path is not a part of the drive description.

Example:
the Debug.Print fso.GetFileName ( "C: \ ABC \ test.txt") 'Now window "test.txt"

8, GetFolder method

Syntax: object.GetFolder (folderspec)

Action: returning a path to the specified folder corresponding Folder object.

Example:
Dim fd
the Set fd = fso.GetFolder ( "c: \ windows") 'variable f represents the target folder windows
Note: If the specified folder does not exist, an error occurs.

9、GetSpecialFolder 方法

Syntax: object.GetSpecialFolder (folderspec)

Role: Returns the specified special folder.

Description:
The folderspec parameter can be any of the following values:

WindowsFolder 0 Windows folder contains files installed by the Windows operating system. 
SystemFolder 1 System folder contains libraries, fonts, device drivers. 
TemporaryFolder 2 Temp folder to store temporary files. Its path in the TMP environment variable.

10、GetParentFolderName 方法

语法:object.GetParentFolderName(path)

Action: Returns a string that specifies the last path member comprising the parent folder name.

示例:
Debug.Print fso.GetParentFolderName("c:\tmp\test.txt")  '显示"c:\tmp"

11, GetTempName method

Syntax: object.GetTempName

Role: useful returns the name of the temporary file or a randomly generated folder, the name of the need to operate a temporary file or folder in execution.

Description: GetTempName method does not produce a file, it only provides a temporary file name, the name can be used to create a file CreateTextFile.

Example:
the Debug.Print fso.GetTempName 'display "radB0208.tmp", changed every time.

12, BuildPath method

Syntax: object.BuildPath (path, name)

Role: Append a name to an existing path.

示例:
Debug.Print fso.BuildPath("c:\tmp", "abc") '显示"c:\tmp\abc"

13, CreateFolder method

语法:object.CreateFolder(foldername)

Action: Create a folder.

Note: If the specified folder already exists, an error occurs.

Example:
fso.CreateFolder ( "c: \ myfolder") 'Create a folder on the C drive myfolder

14, CopyFolder method

Syntax: object.CopyFolder Source, Where do you want [, Overwrite]
Source essential. Indicating one or more strings file folder description replicated folder may include wildcards.  
destination required. Receiving end character string specified in the source folder and subfolders replicated folder, wildcards are not allowed. 
overwrite optional. Boolean value that indicates whether an existing folder is overwritten. If True, files are overwritten. If False, files are not overwritten. The default value is True.

Role: copy a folder to another.

Description:
 ① a wildcard only for the last path component of the source parameter.

For example: fso.CopyFolder "c: \ mydocuments \ letters \ *", "c: \ tempfolder \" It is possible.
But not this: fso.CopyFolder "c: \ mydocuments \ * \ *", "c: \ tempfolder \"

② If the source contains wildcards or destination path separator (\) ending, is that the destination is an existing folder in which the file copy to match the folders and sub-folders. Or that the destination is the name of the file you want to create a folder.

For example: fso.copyfolder "c: \ tmp" , "f: \ abc \"
If there is no disk F abc folder, an error occurred. If there is, you can see the abc folder there tmp folder.
If written like this: fso.copyfolder "c: \ tmp" , "f: \ abc"
at this time if there is no abc, abc will create a folder and copy the contents of tmp folder to the folder abc, rather than tmp folder, only abc is an existing folder, just copy the entire folder to abc tmp folder.

③ If the destination is an existing file, an error occurs.

④ If the destination is a directory, it will try to copy the folder and all its contents. If a source file is included in the already exists in the destination, one error occurs when overwrite is False, otherwise it will attempt to overwrite the file.

⑤ If the destination is a directory read-only, read-only file to this directory when trying to copy and overwrite an existing time to False, an error occurs.

⑥ If the source does not exist or can not use wildcard matching folders and any files, an error also occurred.

⑦CopyFolder method stops on the first error it encounters, before the operation did not disappear, so pay attention.

15, MoveFolder method

Syntax: object.MoveFolder source, destination
before two of the same parameters and CopyFolder.

Action: one or more folders to move from a place to another.

Description:
① only if supported by the operating system, this method allowed to move folders between volumes. Windows is not allowed, the C drive folder to the D drive is not enough.

② If the source contains wildcards or destination path separator (\) ending, the destination specifies that an existing folder in the mobile phase matching files in this folder. Otherwise, that destination is the destination file to create a folder name. This is the same with CopyFolder.

③ If the destination is an existing file, an error occurs.

④ If the destination is a directory, an error occurred.
For example:
fso.movefolder "c: \ tmp", "c:" 'An error occurred.

⑤ If the source does not exist or can not use wildcard matching folders and any files, an error also occurred.

⑥MoveFolder method stops on the first error it encounters. Do not try to roll back any changes made before the error occurred.

16, DeleteFolder method

Syntax: object.DeleteFolder folderspec [, force]

folderspec required. To delete the name of the folder. Folderspec may include wildcards at the end of the path member. 
force optional. Boolean value, if you want to delete the folder has a read-only attribute set, its value is True, if the value is False (the default), you can not delete files with the read-only attribute set of folders.

Role: delete a specified folder and its contents.

Note: If you do not find the file that matches the folder, an error occurs. DeleteFolder method stops on the first error it encounters, do not try to change before any roll back or undo the errors made.

Example:
fso.DeleteFolder ( "c: \ tmp")

17, FolderExists method

Syntax: object.FolderExists (folderspec)

Role: if the specified folder exists returns True, there is no return False.

18, DriveExists method

Syntax: object.DriveExists (drivespec)

Role: if the specified drive exists, returns True, if there is no return False.

19, FileExists method

语法:object.FileExists(filespec)

Role: If the specified file exists, returns True, if it exists, False is returned.

20, CreateTextFile method

语法:object.CreateTextFile(filename[, overwrite[, unicode]])

overwrite optional. Boolean value that indicates whether an existing file may be overwritten. Which may be covered if the value is True, it can not cover the value is False. If it is omitted, the file already exists can not be overwritten.

unicode optional. Boolean value that indicates the file is created as a Unicode file or as an ASCII file created. If, as a Unicode file is created, its value is True, created as an ASCII file, its value is False. If omitted, then that is an ASCII file.

Role: Creates a specified file name and returns a TextStream object for the file read and write.

示例:
Dim f
Set f = fso.CreateTextFile("c:\testfile.txt", True)

21, OpenTextFile method

语法:object.OpenTextFile(filename[, iomode[, create[, format]]])

Role: Opens a specified file and returns a TextStream object that can be used to file read, write, append operation.

Description:
· The iomode parameter value may be set to any value in the following:

ForReading 1 Open a read-only file, the file can not be written on it. 
ForWriting 2 to open a file for write operations. If the file and the file with the same name already exists, overwriting the previous contents. 
ForAppending 8 to open a file and write the end of the file.

Note: there is no help in VBA ForWriting, in fact, is there, VBA Help is also wrong. Further, before the first use of these constants in the statement, or directly value.

· Create optional, which indicates if the specified filename does not exist if you can create a new file. If you create a new file, its value is True. Create a file if its value is False. The default value is False.

· Format parameter value may be set to any value in the following:

TristateUseDefault -2 open the file using the system default. 
TristateTrue -1 open the file in Unicode format. 
TristateFalse 0 Open the file in ASCII format.

Example:
Dim F
the Set F = fso.OpenTextFile ( "C: \ Testfile.txt", 2, True)
or:
Const = 2 ForWriting
the Set F = fso.OpenTextFile ( "C: \ Testfile.txt", ForWriting, True)
both functions are the same, a declared constant, a direct use value. We are in the C drive to create a file testfile.txt (if not exist), or to write the way open (if present).

22, CopyFile method

语法:object.CopyFile source, destination[, overwrite]

Role: to copy one or more files from one place to another.

Description: Local and CopyFolder Note that totally similar.

Example:
fso.copyfile "C: \ Testfile.txt", "F: \ abc \" 'abc if an error does not exist.
fso.copyfile "c: \ testfile.txt", "f: \ abc" ' abc if it does not exist to replicate testfile.txt F disk the file name into abc, abc if there is, error, because it is a directory.

23, MoveFile method

Syntax: object.MoveFile source, destination

Action: one or more files from one place to another.

Description: Local and MoveFolder Note that totally similar.

24, DeleteFile method

语法:object.DeleteFile filespec[, force]

Role: delete a specified file.

Description: force optional. If you want to remove files with read-only attribute set, its value is True. If its value is False (default), the file can not be deleted with the read-only attributes set. 

 

(C) processing driver

Drive object can be used to obtain information about the various drives, Drive object attributes are:

The total capacity of the drive TotalSize attribute, in bytes.
AvailableSpace properties of the drive capacity of the available space, in bytes.
The remaining space capacity FreeSpace properties of the drive, and AvailableSpace attributes are the same.
    Support for limits of computer systems, it may be different between the two.
Attribute DriveLetter drive letter, that is the letter.
Type DriveType properties of the drive. The "Removable", "Fixed", "Network", "CD-ROM", "RAM Disk"
Serial No. SerialNumber properties of the drive.
The file system type FileSystem attributes used by the drive. Such as FAT, FAT32, NTFS, and CDFS.
Attribute IsReady drive is available.
Network share name ShareName properties of the drive.
Volume name VolumeName properties of the drive.
Path properties of the drive path. Path C drive is C :, rather than C: \.
RootFolder properties given drive root folder. The root folder of the C drive folder is C: \.

Using these attributes are very simple, you can directly use the "object. Attribute" the. Before using the first to get a Drive object with the GetDrive, be careful not to create a drive object. Below is an example:

Sub ShowFreeSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.Getdrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & "-"
    s = s & d.VolumeName & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace / 1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub

Use Call ShowFreeSpace ( "c:"), you can get the C drive volume name and the available space.

(D) processing folder

1, to obtain information folder

Folder object can be used to get information about folders, Folder object's properties are:

Property Attributes properties of the folder. It may be any one or any combination of the following logic values:
    Normal 0 general files. Property is not set. 
    ReadOnly 1 Read-only file. Property is read / write. 
    Hidden 2 hidden files. Property is read / write. 
    System 4 system files. Property is read / write. 
    Volume 8 disk drive label. Property is read-only. 
    Directory 16 folder or directory. Property is read-only. 
    Archive 32 has been changed since the last backup file. Property is read / write. 
    Alias 64 links or shortcuts. Property is read-only. 
    Compressed 128 compressed files. Property is read-only. 
Name Properties folder name.
Short name ShortName property earlier 8.3 naming conventions used by the program.
Type Properties folder type.
Files Files File attributes of all objects in the collection of File objects contained in the specified folder
    ── including setting up those files hidden and system file attributes.
Drive properties of the folder where the drive letter.
IsRootFolder attribute folder is the root folder.
ParentFolder parent file attributes folder object.
Set of subfolders SubFolders properties of the folder.
Path Path properties of the folder.
Short path ShortPath property earlier 8.3 file naming convention used by the program.
Size The size of a folder attribute, in bytes.
DateCreated properties file creation date and time of the clip.
Last DateLastModified attribute modification date and time the folder.
DateLastAccessed property last access date and time the folder.

Drive object properties and use are the same, you can obtain a Folder object with GetFolder, you can create a Folder object with CreateFolder method of the FileSystemObject object.

2, the method of the Folder object

⑴Copy method

语法:object.Copy destination[, overwrite]

Role: to a specified folder copied from one place to another.

Description: CopyFolder method FileSystemObject object and effect of the Copy method is the same, except that the latter can copy more folders.

⑵Move method

Syntax: object.Move destination

Role: a specified folder from one place to another.

Description: The role and FileSystemObject.MoveFolder Move method is the same. Except that the latter may move multiple folders.

⑶Delete method

Syntax: object.Delete force

Role: delete a specified folder.

Description: The role and FileSystemObject.DeleteFolder Delete method is the same.

⑷CreateTextFile method

语法:object.CreateTextFile(filename[, overwrite[, unicode]])

Role: CreateTextFile and method of the FileSystemObject object is the same.

Example:
    the Set fd = fs.getfolder ( "c: \ tmp")
    the Set f = fd.CreateTextFile ( "testfile.txt", True)
can create files in the C drive testfile.txt tmp folder.


(E) processing file

1, to obtain information file

File object can be used to obtain information about file attributes and the File Folder object's properties are exactly the same, but less Files property, IsRootFolder property, SubFolders attribute these three attributes. Here it is not a column.

2, File object methods

⑴Copy method

⑵Move method

⑶Delete method

It is completely analogous to the above three methods and Folder, syntax, same can also be replaced by a corresponding method FileSystemObject object.

⑷OpenAsTextStream method

语法:object.OpenAsTextStream([iomode, [format]])

Role: Opens a specified file and returns a TextStream object that can be used to read files, write, append operation.

Description: This method is the same method OpenTextFile FileSystemObject object and function. Parameters are also the same.


(F) with text files

1, open or create a text file

Open an existing text file, OpenAsTextStream method can use the FileSystemObject object OpenTextFile method or File object.
The method can be used to create the file CreatTextFile FileSystemObject object or method will OpenTextFile iomode parameter is set ForWriting = 2, create parameter is set to True.
For example:
the Set f = fso.OpenTextFile ( "c: \ test1.xls", 2, True) 'If test1.xls does not exist will be created automatically.

2, read the file

After opening the file, returns a TextStream object, we can use the file read and write TextStream object properties and methods.

Look at several properties TextStream object.

· AtEndOfLine properties just a file pointer marks the end of the preceding line
· AtEndOfStream attribute file pointer is at the end of the file TextStream
· Column TextStream file attribute column number of the current character position
· Line attribute file TextStream current line number

Use TextStream object There are three ways to read the file.

· Read method

Syntax: object.Read (characters)

Function: the number of characters read from a specified file and returns a string TextStream obtained.

Example:
Sub du ()
Dim FSO, A, retstring
Const. 1 = ForReading
the Set FSO = the CreateObject ( "Scripting.FileSystemObject")
the Set A = fso.OpenTextFile ( "C: \ Testfile.txt", ForReading, False)
the Do the While A .AtEndOfLine <> True 'if the end of the line
    retstring = retstring & a.Read (1) ' read a character
Loop
a.Close
the Debug.Print retstring 'can be seen that read the characters of the first row
end Sub

· ReadLine method

Syntax: object.ReadLine

Function: read a file from a TextStream entire row (but not including, the newline newline) and returns a string obtained.

Example:
Sub du_line ()
Dim FSO, A, retstring
Const. 1 = ForReading
the Set FSO = the CreateObject ( "Scripting.FileSystemObject")
the Set A = fso.OpenTextFile ( "C: \ Testfile.txt", ForReading, False)
the Do the While A .AtEndOfStream <> True 'end of the file is in TextStream
    retstring = a.ReadLine' reads one line
    Debug.Print retstring 'displayed in the window immediately
Loop
a.Close
end Sub

· ReadAll method

Syntax: object.ReadAll

Function: read the entire file and returns a string of TextStream get.

Note: For large files, use the method ReadAll waste of memory resources. Other techniques should be used to input a file, such as file read by row.

示例:
Sub du_all()
Dim fso, a, retstring
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set a = fso.OpenTextFile("c:\testfile.txt", ForReading, False)
retstring = a.Readall   '全部读取
Debug.Print retstring
a.Close
End Sub

There are two methods of assisted reading:

· Skip method

Syntax: object.Skip (characters)

Function: Skips a specified number of characters when reading a TextStream file.

Example:
Sub duskip ()
Dim FSO, A, retstring
Const. 1 = ForReading
the Set FSO = the CreateObject ( "Scripting.FileSystemObject")
the Set A = fso.OpenTextFile ( "C: \ Testfile.txt", ForReading, False)
the Do the While A .AtEndOfLine <> True 'if the end of the line
    retstring = retstring & a.Read (1) ' read a character
    a.Skip (1) 'a character skip
Loop
a.Close
the Debug.Print retstring' you can be seen read the first line of the odd bit of character
End Sub

· SkipLine way

Syntax: object.SkipLine

Function: Skip the next line when reading a TextStream file.


3, writing data to a file

Write data to a file There are three ways.

· Write method

Syntax: object.Write (string)

Function: Write a string to a specified TextStream file.

示例:
Sub xie()
    Const ForWriting = 2, ForAppending = 8
    Dim fs, f
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.OpenTextFile("c:\testfile.txt", ForAppending,TristateFalse)
    f.Write "Hello world!"  '写入字符串
    f.Close
End Sub

· WriteLine method

Syntax: object.WriteLine ([string])

Function: Writes a specified string and newline character to a TextStream file.

Example:
f.WriteLine ( "! The Hello World") 'writes the string, plus a newline.

·WriteBlankLines 方法

语法:object.WriteBlankLines(lines)

Function: Writing to a specified number of newline TextStream file.

Example:
f.WriteBlankLines (3) 'is equivalent to three times by ENTER.

4, close the file

TextStream object using a Close method, the above example has been very simple.


(Vii) summary

    From the above description, we see the use of FileSystemObject object processing files, folders, have characteristics more easily than existing methods using VBA statement. This is because the FileSystemObject object using object-oriented syntax. In addition FileSystemObject object with text files favorably to the VBA statements, highly recommended. The only problem is can not handle binary files, Microsoft said in a document related to planned future support for binary files, but should just plan it, huh, huh.

Guess you like

Origin www.cnblogs.com/medik/p/11026445.html