Four methods of file operations two Excel-VBA

Four methods of file operations two Excel-VBA

Second, the use VBA file handling statements to process the file

    VBA contains a number of statements and functions for file operations, file operations to meet the requirements in most cases. Here we were introduced one by one in accordance with the operational purposes.

(A) document processing
    
1.Name statement

语法:Name oldpathname As newpathname

Function: rename a file, directory, or folder, move a file.

Note: Use the Name on one open file, an error will occur. When a file operation, must pay attention to error handling.

Example:
the On the Resume the Next Error 'Error Handling
Name "f: \ TEST.xls" As "f: \ TEST123.xls"' Rename
Name "f: \ TEST.xls" As "f: \ dll \ TEST.xls" 'mobile file
name "f: \ TEST.xls" As "d: \ TEST123.xls"' across the drives move and rename the file

Note: Name can not move a directory or folder.

2, FileCopy statement

Syntax: FileCopy source, destination

Function: Copy a file.

Note: If you use the FileCopy statement to open a file, an error occurs.

Example:
the FileCopy "F: \ Test.xls", "E: \ Test.xls" 'Copy Test.xls from F to E drive disk

3, Kill statement

Syntax: Kill pathname

Function: delete the file from the disk.

Description: (?) Kill supports multiple character (*) and single character wildcards to specify multiple files. If you use Kill to delete an open file, an error occurs.

Example:
Kill "f: \ TEST.xls" 'F disk TEST.xls delete files
Kill "f:. \ * Xls "' Delete all F disk xls file

4, GetAttr function

Syntax: GetAttr (pathname)

Function: Gets a file, directory, or folder's properties. It returns an Integer value.

return value

GetAttr by the value returned is the sum of the values ​​of the following properties:

Constant Value Description 
vbNormal 0 General 
vbReadOnly 1 read-only 
vbHidden 2 Hide 
vbSystem 4 system file
vbDirectory 16 directory or folder 
vbArchive 32 archive 
vbalias 64 specified file name is an alias. It is only available for Macintosh.

Description: To determine whether an attribute is set, using the comparison with the bitwise And operator between the function and the property value desired GetAttr learned. If the results obtained are not zero, then the value of this attribute is set.

Example:
Debug.Print the GetAttr ( "F: \ test.txt") 'If it is an archive file, the window can immediately see the value of 32
Debug.Print the GetAttr ( "F: \ test.txt")' attributes - Senior - after removing the hook can archive the value of 0

To determine whether a read-only file, dismount available:
the Debug.Print the GetAttr ( "F.: \ Test.txt") vbReadOnly And
if a non-zero value, when the read-only instructions.

5, SetAttr statement

Syntax: SetAttr pathname, attributes

Function: Set the properties for a file.

Note: If you want to open a file set properties, run-time error results.

Example:
the SetAttr "F: \ test.txt", vbHidden 'set the hidden attribute.
SetAttr "F: \ test.txt", vbHidden + vbReadOnly ' is set to hide and read only.

6, FileLen function

Syntax: FileLen (pathname)

Function: Get the length of a file, in bytes.

Description: When calling FileLen function, do not open the file, if the specified file is already open, the returned value is the size of the file before the open.

7, FileDateTime function

Syntax: FileDateTime (pathname)

Function: Gets the date and time after a file was created or last modified.

Example:
the Debug.Print the FileDateTime ( "F.: \ Test.xls") 'can be seen in the window immediately 2007-3-29 19:28:27


(B) processing directory

1, CurDir function

Syntax: CurDir [(drive)]

Function: Returns the current path.

Description: drive parameter is optional, it is the presence of a specified drive. If no drive, or a drive is a zero-length string ( ""), returns the current drive CurDir path.

示例:
Debug.Print CurDir      ' 返回“C:\Documents and Settings\yc\My Documents”。
Debug.Print CurDir("C")     ' 返回“C:\Documents and Settings\yc\My Documents”。
Debug.Print CurDir("D")     ' 返回“D:\”。

2, ChDir statement

Syntax: ChDir path

Function: to change the current directory or folder.

Description: ChDir statement to change the default directory location, but will not change the default drive location. C. default drive is typically

Example:

ChDir "D: \ the TEMP"
Debug.Print the CurDir 'return to "C: \ Documents and Settings \ yc \ My Documents".
Debug.Print CurDir ( "D") 'returns "D: \ temp".
Comparison with the previous example, this time in the current directory D drive has been changed to "D: \ temp", but the default drive or C.

3, ChDrive statement

Syntax: ChDrive drive

Function: to change the current drive.

Note: If a zero-length string ( ""), the drive current will not change. If there is more than one character drive parameters, then ChDrive only use initials.

Example:
the ChDrive "D"
the ChDir "D: \ TEMP"
the Debug.Print the CurDir 'Back "D: \ temp".
Debug.Print CurDir ( "D") 'returns "D: \ temp".

Compared with the previous embodiment, with CurDir returns "D: \ temp", the drive current has become a D.

4, Dir function

Syntax: Dir [(pathname [, attributes ])]
      two parameters are optional, attributes indicate the file attributes.
Function: Returns a file name, directory name or folder name, which must match a specified pattern or file attribute, or a disk label.

Note: The first time you call the Dir function, you must specify pathname, otherwise it will generate an error. If you also specify the file attribute, then it must include the pathname.

Dir returns the first file name that matches pathname of. If you want to get other matching pathname of the file name, and once again call Dir, and do not use parameters. If the file is not in line with the conditions, the Dir returns a zero-length string ( ""). Once the return value is zero-length string, and to call Dir again, you must specify pathname, otherwise it will generate an error. Do not have access to all match the current pathname of the file name, you can change to a new pathname. However, it can not be called recursively Dir function. VbDirectory to call the Dir property can not be continuously returned subdirectory.

Example:
Debug.Print Dir ( "F: \ TEST.XLS") 'returns "TEST.XLS"
Debug.Print Dir ( "F:. \ * XLS")' Returns the file name under Condition finds.
Debug.Print Dir ( "F:. \ * Txt", vbReadOnly) ' Returns a read-only file txt

The following procedure displays all the directories in the root directory C.
Sub DirC ()

= MyPath "C: \"   
MyName the dir = (MyPath, the vbDirectory) 'Find the first entry.
Do While MyName <> "" 'to start the cycle.
    'Skip the current directory and parent directory.
    MyName IF <> "." And MyName <> ".." the Then
        'bits using a comparison to determine the representative directory MyName.
        IF (the GetAttr (MyPath & MyName) And the vbDirectory) = the vbDirectory the Then
            the Debug.Print MyName 'if it is a directory, the name is displayed.
        The If End
    End the If
    MyName = dir 'to find the next directory.
Loop

End Sub

The following recursive procedure can find all files in the directory and subdirectories.

Public Sub FindFile(mPath As String, Optional sFile As String = "")
On Error Resume Next
Dim s As String, sDir() As String
Dim i As Long, d As Long

If Right(mPath, 1) <> "\" Then
    mPath = mPath & "\"
End If
'查找目录下的文件
s = dir(mPath & sFile, vbArchive + vbDirectory + vbHidden + vbNormal + vbReadOnly + vbSystem)
Do While s <> ""
   Debug.Print mPath & s
   s = dir
Loop
'查找目录下的子目录
s = dir(mPath, vbArchive + vbDirectory + vbHidden + vbNormal + vbReadOnly + vbSystem)
Do While s <> ""
    If s <> "." And s <> ".." Then
        If (GetAttr(mPath & s) And vbDirectory) = vbDirectory Then
        d = d + 1
        ReDim Preserve sDir(d)
        sDir(d) = mPath & s
        End If
    End If
    s = dir
Loop

'Recursion starts        
the For I = D. 1 the To
    the FindFile sDir (D) & "\"
the Next

End Sub


5, MkDir statement

Syntax: MkDir path

Function: Create a new directory or folder.

Description: path may comprise a drive. If you do not specify a drive, then MkDir creates a new directory or folder on the current drive.

Example:
MkDir "MYDIR" 'create a new directory or folder in the current directory.

6, RmDir statement

Syntax: RmDir path

Function: delete an existing directory or folder.

Note: If you want to use RmDir to delete a directory that contains the folder or file, an error occurs. Before attempting to delete a directory or folder, first use the Kill statement to delete all files.

Example:
RmDir "MYDIR" 'will MYDIR deleted.

 

C) text files

1, Open sentence

语法:Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

Which access, lock, reclength is optional and generally do not.
mode specified to open files. There are five:
the Input: Open the input, i.e., the reading mode.
Output: output opened, i.e. write mode.
Append: to append Open, is added to the end of the file.
Binary: Open in binary mode.
Random: open in a random manner, if the mode is not specified, Random open the file.

filenumber is a valid file number, in the range between 1-511. Can be specified, the function may be obtained using FreeFile next available file number.

Note: If the pathname specified file does not exist, then, when, Binary, Output, or Random open the file with the Append, can create this file.

Example:
the Open "F.: \ Test.txt" of As the For the Input #. 1 'to enter Open
Open "F: \ TEST.xls" For Binary As # 1' opened in binary mode

2, Close statement

Syntax: use Close [filenumberlist]
     filenumberlist parameters for one or more file number, if omitted filenumberlist, all active files Open statement to open will be closed.

Note: After opening the file, the file must be closed after use.

Example:
Dim the I, FileName
the For the To the I =. 3. 1    
    FileName = "the TEST" the I & 'create filenames.
    Open FileName For Output As #I 'to open the file.
    Print #I, "This is a test ." ' String written to the file.
The I the Next
use Close 'three open files closed.

3, Reset statement

Syntax: Reset

Function: Close all with the Open statement to open a disk file.

Description: Reset statement to close the Open statement to open files of all the activities, all the contents of the file buffer is written to disk.

Example:
Dim the FileNumber
the For the FileNumber =. 5. 1 the To    
    the Open "the TEST" the FileNumber the For the Output of As & filenumber
    the Write filenumber, "the Hello World" 'to write data to a file.
FileNumber the Next
the Reset 'Close the data in the file and buffer written to disk.

4, FreeFile function

Syntax: FreeFile [(rangenumber)]
      parameter rangenumber specify a range, in order to return the next available file number within this range. Specifies 0 (default) returns a number between 1 - File No. 255.. 1 returns a specified range 256-- 511 between the file number.

Function: to provide an unused file number.

Example:
Dim FNUM of As Integer

fnum = FreeFile

Open "F:\TEST.txt" For Input As #fnum

Close #fnum


5, EOF function

Syntax: EOF (filenumber)

Function: Returns a Integer, which contains the Boolean value True, show that has reached the end of Random or sequential Input to open the file.

6, LOF function

Syntax: LOF (filenumber)

Function: Returns a Long, Open statement represented by the size of open files, the size in bytes.

7, Loc function

Syntax: LOc (filenumber)

Function: Returns a Long, specify the current read / write position in the open file.


8, Input # statement

Syntax: Input #filenumber, varlist

Function: variable assigned to read out the data from the sequential file has been opened in.

Description: Write # is usually the Input # statement read data written to the file. To be able to use Input # statement to read data files into the correct variable, when data is written to a file, to be used instead of using the Write # statement Print # statement. Write # using statement ensures that individual data fields correctly separated.

Example:
This example uses the Input # statement to read in the data file into two variables. This example assumes that the file containing the data rows TESTFILE Write # statements are written in; that is, each row of data in the portion of the string is enclosed in double quotation marks, the numbers separated by commas with, e.g., ( " Hello ", 234).

MyString Dim, the MyNumber
the Open "TESTFILE" of As the For the Input #. 1 'to open the input file.
Do While Not EOF (1) 'recycled to the end of the file.
    Input # 1, MyString, MyNumber 'read the data into two variables.
    Debug.Print MyString, MyNumber 'immediately display the data in the window.
Loop
use Close # 1 'close the file.

9, Write # statement

语法:Write #filenumber, [outputlist]

Function: write data to a sequential file.

Description: usually Input # reads data from a file Write # writes.
If you omit outputlist, and add a comma after filenumber, it will be a blank line will print to a file. Available gap between a plurality of expressions, separated by commas or semicolons. Blank and semicolon equivalent.

Write # will follow with a few common convention when writing data to a file, so that no matter what area are available Input # reads and correct interpretation of the data:

· The total period is the decimal separator value when writing data.

• For Boolean data type, or print or print # TRUE # # FALSE #. No matter in what area, not to True and False two keywords translated.

Use common date format Date type of data written to the file. When the member is lost or zero date or time, only a partial write existing file.

If outputlist data is Empty, not any data written to the file. But Null data, will have to write # NULL #.

If outputlist data is Null data, will be written to the file # NULL #.

• For Error type of data, the output looks like the #ERROR errorcode #. No matter in what area, not the translated keyword Error. 
And Print # statement different, when data is to be written to the file, Write # statement commas inserted between items and quotation marks to the string. No need to type the specific delimiter in the list. Write # statement after the outputlist the last character written to the file will insert a new line character, that is, carriage return line feed, (Chr (13) + Chr (10)).

Example:
the Open "F.: \ Test.txt" the For the Output of As #. 1 'to open the output file.
Write # 1, "Hello World" , 1234 ' is written in a comma-separated data.
Write # 1, 'write blank lines.

MyBool Dim, MyDate, MyNull, MyError with the
'Assignment Boolean, Date, Null Error, and the like.
= False MyBool: MyDate = #February 12 is, # 1969: MyNull = Null
MyError with the CVErr = (32767)
'Boolean data is written to # TRUE # or # FALSE # format.
'Date is written in a common format, such as: # # 1994-07-13 behalf of
' 13 January 1994. Null data is written to # NULL # format. 
'Error data is written to the error code # #ERROR format.
The Write #. 1, MyBool; "IS A Boolean value"
the Write #. 1, MyDate; "IS A DATE"
the Write #. 1, MyNull; "IS A null value"
the Write #. 1, MyError with the; "IS AN error value"
the Close #. 1 'close the file.

We can see what is written:
"the Hello World", 1234

#FALSE#," is a Boolean value"
#1969-02-12#," is a date"
#NULL#," is a null value"
#ERROR 32767#," is an error value"

10, Line Input # statement

语法:Line Input #filenumber, varname

Function: read a line from a sequential file and open it assigned to the String variable.

Note: Print # usually used in conjunction with the Line Input # statement.
Line Input # statement to read from a file only once a character, until it encounters a carriage return (Chr (13)), or carriage return - newline character (Chr (13) + Chr ( 10)) so far. Carriage return - line feed is skipped without being attached to the string.

Example:
Dim The TextLine
the Open "TESTFILE" of As the For the Input #. 1 'to open the file.
Do While Not EOF (1) 'recycled to the end of the file.
    Line Input # 1, TextLine 'reads one line data and a given variable.
    Debug.Print TextLine 'displayed in the data window immediately.
Loop
use Close # 1 'close the file.

11, Input Function

Syntax: Input (number, [#] filenumber)
where number specifies the number of characters to return.

Function: Returns the String, which contains Input or Binary file opened in character.

Description: usually written file or Print # Put Input data read out function. Input function only, in an Input or Binary file opened.
Input # statement with different, Input function returns the character read it all, including commas, carriage returns, blank column, line feeds, quotation marks, and leading spaces and so on.

Example:
Dim the MyChar
the Open "F: \ test.txt" of As the For the Input #. 1
the Do Not the While the EOF (. 1) 'recycled to the end of the file.
    MyChar = Input (1, # 1 ) ' reads a character.
    Debug.Print MyChar 'to the display window immediately.
Loop
use Close # 1

The following function can be a text file data is read into a character string (to be wrong if it contains Chinese, because a text 2 bytes).

Public Function ReadText(FileName As String)

Dim fnum%, isopen As Boolean
On Error GoTo erro
fnum = FreeFile()
Open FileName For Input As #fnum
isopen = True
ReadText = Input(LOF(fnum), fnum)

erro:
    If isopen Then Close #fnum
    If err Then Debug.Print err.Number, err.Description

End Function

12, Print # statement

Syntax: Print #filenumber, [outputlist]

outputlist set parameters is as follows:
[{Spc (n-) | the Tab [(n-)]}] [expression The] [charpos]

SPC (n) is used to insert a blank character in the output data, and n denotes the number of characters to be inserted in the blank. 
Tab (n) is used to position the insertion point at a certain absolute column number, Here, n is the column number. Using the non-parametric Tab insertion point start position of a next print area. 
expression numeric or string expression to be printed. 
next charpos specify a character insertion point. Semicolon positioned after the insertion point on a displayed character. Tab with (n-) the insertion point is positioned on a certain absolute column number, with no parameters Tab position the insertion point at the beginning of the next print region. If omitted charpos, the next character in the next line printing.


Function: the display format data file write sequence.

Description: Print # usually reads out the data written in the file using the Line Input # or Input.

Example:
the Open "F.: \ Test.txt" the For the Output of As #. 1 'to open the output file.
Print # 1, "This is a test" ' text data written to the file.
Print # 1, 'will be written to the file blank lines.
Print # 1, "Zone 1" ; Tab; "Zone 2" ' two data write area (print zones).
Print # 1, "Hello"; ""; "World" ' two strings separated by spaces.
Print # 1, Spc (5) ; "5 leading spaces" ' before the string is written five spaces.
Print # 1, Tab (10) ; "Hello" ' to write data in the tenth column.

'Assignment Boolean, Date, Null, and Error and so on.
MyBool Dim, MyDate, MyNull, MyError with the
MyBool = False: MyDate = # 2/12 is / # 1969: MyNull = Null
MyError with the CVErr = (32767)
'True, False, and Null Error automatically converted according to the format of the system area setting.
'Short Date Format The date in standard display.
The Print #. 1, MyBool; "IS A Boolean value"
the Print #. 1, MyDate; "IS A DATE"
the Print #. 1, MyNull; "IS A null value"
the Print #. 1, MyError with the; "IS AN error value"
the Close #. 1

SUMMARY The above code is written as follows:
This IS A Test

Zone 1        Zone 2
Hello World
     5 leading spaces 
         Hello
False is a Boolean value
1969-2-12  is a date
Null is a null value
Error 32767 is an error value

13, Width # statement

Syntax: filenumber the Width, width
width necessary. Numeric expression in the range of 0-255, before the start of a new line, pointing out how many characters can appear on the line. If the width is equal to 0, the line length is not limited. The default value of 0 width.

Function: the width of the output line specified by the Open statement to open files.

Example:
Dim the I
the Open "F: \ testfile.txt" the For the Output of As #. 1
the Width #. 1, 5 'of output line width of 5.
For I = 0 To 9 '10 cycles.
    Print # 1, Chr (48 + I); ' output five characters per line.
The I the Next
use Close # 1

SUMMARY The above code is written as follows:
01234
56789

 

(D) handle binary files
open binary file can use the Open statement to open Random and Binary mode. Reading and writing binary file using the Get and Put statements.

1, Put statement

语法:Put [#]filenumber, [recnumber], varname

recnumber optional. Variant (Long). Record number (Random document mode) or several (Binary mode file) byte indicating where to start writing.

Description: Get usually read file data Put written out.

Example:
Dim NUM of As Long, String text of As
NUM = 12345
text = "A String"
the Open "F: \ data.bin" Binary the For # of As. 1 'to create a binary file or to open
Put # 1,, num' write 4 byte
Put # 1,, text 'writes 8 bytes (length of string. 8)
the Close. 1 #


2, Get statement

语法:Get [#]filenumber, [recnumber], varname

recnumber optional. Variant (Long). Record number (Random document mode) or several (Binary mode file) byte to indicate read data starts here.

Function: open a disk file is read into a variable.

Description: Get data is typically written to a read-out file Put.

Example: Reading the contents of the above codes written
Dim NUM of As Long, String text of As
the Open "F: \ data.bin" of As #. 1 Binary the For
the Get #. 1,, NUM
text = Space $ (. 8) 'prepared eight words section string
Get # 1,, text 'reads
the Debug.Print NUM, text
the Close. 1 #

In the Immediate window you can see the following:
 12345 A String


3, Seek statement

Syntax: Seek [#] filenumber, position
where the position is between 1 to 2,147,483,647 (corresponding to 2 ^ 31--1) between the number indicating the position of the next read or write operation is to occur.

Function: Open statement to open the file, set the next read / write operation position.

Description: Get the reading position can be specified by the statement Seek statement, the Get and Put specified in the statement where the specified number will be covered by the Seek statement file location.

Example:
Dim the MaxSize, NextChar, the MyChar
the Open "TESTFILE" of As the For the Input #. 1     
the MaxSize LOF = (. 1) 'acquires the total number of characters of the file.
'All the recording cycle time, but starting from the last record read forward.
The To the MaxSize = NextChar. 1 for the Step -1    
    the Seek #. 1, NextChar 'a read-write position.
    MyChar = Input (1, # 1 ) ' reads a character.
NextChar the Next
use Close # 1  

4, Seek function

Syntax: Seek (filenumber)

Function: Returns a Long, specify the current read / write position in the Open statement to open the file.

Note: When using the Get statement to read the file, you must use LOF function to determine whether the end of the file is reached, rather than using the EOF function. Seek function can determine the current position, and then compared with the value of LOF.

Example:
the Do the While the Seek (. 1) <LOF (. 1)
   'continues to read
   ......
Loop

 

(E) summary

      VBA file the statement of operations covers most of the contents of the file operations, many use the function is also very simple, the general file read and write is very convenient, especially for text files. But for complex read and write files, configuration and maintenance of the code is not good. Therefore, after VB6, Microsoft introduced FileSystemObject object model, the object-oriented class library is provided to operate the drive, folders and files. But for working with binary files, currently only use VBA statement.
      Excel file itself is a binary file, it uses the file format is called BIFF (Binary Interchange File Format), that is exchangeable binary file format (but 2007 started using OOXML format). On its internal structure, we also study. Binary structure open the Excel file, it can not only read the data in the table, you can also read all of their information (including passwords). Note that the Open statement to open the file, not our usual double-click to open a file to the screen, but store it on disk reads data into the buffer, not the visualization open. This does not require a password to open, even if you set the Excel file open password, or not wrong according to open, which is the root cause of insecurity Excel file is located. I sent an article about the break before the crack inside the VBA project password is to replace the binary. As the forum not to discuss the topic of crack, there is no longer a detailed analysis of the code, please interested in their own research. Of course, other Excel password crack similar may also, provided that you have to fully understand the internal structure of Excel, and know where to put the password in order to replace. Decrypt know, of course, it can be targeted to improve the encryption method. Well, without further ado here, if interested in the internal structure of Excel, you can look at this article, read to say.

Guess you like

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