One of the four methods Excel-VBA file operations

When we use every day in Excel, will not only use the data in the current Excel file, often you need to access other data files. These data files may be Excel files, text files, or database files. Friends often ask how to operate these data files in vba code? This paper systematically introduce the method of application VBA manipulate data files in Excel.

This paper describes the four commonly used methods:
1, using the Excel object to process the file;
2, using the document processing VBA statement to process the file;
3, using FileSystemObject object to process the file;
4, using the API function to process the file.

Of course, for database files, you can also use ADO + SQL method of operation, but the Forum has been described in detail predecessors such methods, we will not repeat it.

First, using the Excel object to handle the file

To manipulate the file is the most convenient and easiest way to take advantage of native Excel object.
We mainly use the method to manipulate files and Workbook Workbooks collection objects.

1, open the Excel file

We can open an Excel workbook with Workbooks.Open method.
Workbooks.Open (FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
  where FileName is a required parameter, said to open the workbook name, If you do not specify a path, representing the current path. Further 14 is an optional parameter, in addition to encryption parameter, the other seldom used. Specific meaning can be found in the help of VBA.
Example:
   Workbooks.Open "F: \ test.xls"
can open the file test.xls F disk.

2, open the text file

  Use the Open method can also open a text file, but it is recommended to use the OpenText method. This method is to load a text file is parsed and treated as a single workbook contains a worksheet, then placed in the text file data is subjected to breakdown in the process of this sheet. The full syntax is:
Workbooks.OpenText (FileName, Origin, StartRow, DataType, TextQualifier, ConsecutiveDelimiter, the Tab, Semicolon, Comma, Space, Other, OtherChar, FieldInfo, The TextVisualLayout, DecimalSeparator, the thousandsSeparator, TrailingMinusNumbers, Local)

Specific meanings of the above parameters can be found in the VBA help, not repeat it here. In actual programming, generally without the parameters of these complex processes. You can get open a text file of VBA code by recording the macro. The specific method is to choose the "File - Open" and then select to open the text file, the Text Import Wizard will appear, complete step by step execution, until the text opens, stop recording.
The following is the code obtained by recording a macro:
Sub Macro1 ()
'
' Macro1 Macro
'Macro recorded by MC SYSTEM, time: 2007-3-29
'

'
    Workbooks.OpenText Filename:="F:\CallWindowProc.txt", Origin:=xlWindows, _
        StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False _
        , Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
        TrailingMinusNumbers:=True
End Sub

In the actual programming as long as the appropriate changes can be made use of.

3, open other files

Using Excel Objects can also open the XML file and some database (such as Access) file, the corresponding XML file, you need more than Excel2003 version.

Method OpenXML syntax is as follows:
Workbooks.OpenXML (Filename, Stylesheets, the LoadOption)
FileName String type is necessary. To open a file name.

Stylesheets Variant Optional. An array of values ​​or a single value, which specifies the XSL Transformations (XSLT) stylesheets processing instruction to be applied.

LoadOption Variant type conversion. Specifies the Excel opens XML data files. XlXmlLoadOption may be one of the constants.

XlXmlLoadOption XlXmlLoadOption be one of the following constants: 
xlXmlLoadImportToList the contents of the XML data file is placed XML list. 
xlXmlLoadMapXml display architecture XML data file in the "XML Structure" task pane. 
xlXmlLoadOpenXml open the XML data file. Contents of the file will start. 
xlXmlLoadPromptUser prompt the user to choose to open the files.


Example
The following code opens the XML data file "customers.xml" and shows the contents of this file in XML list.

Sub UseOpenXML()
    Application.Workbooks.OpenXML _
        Filename:="customers.xml", _
        LoadOption:=xlXmlLoadImportToList
End Sub

OpenDatabase method has the following syntax:
Workbooks.OpenDatabase (FileName, the CommandText, the CommandType, the BackgroundQuery, ImportDataAs)

FileName String type, is necessary. Connection string.

CommandText Variant Optional. Command text query.

CommandType Variant Optional. Type command query. The following are the available commands type: Default, SQL and Table.

BackgroundQuery Variant Optional. Query background.

ImportDataAs Variant Optional. Determine the format of the query.

Example
In this example, Excel opens the "northwind.mdb" file.

Sub OpenDatabase()

Workbooks.OpenDatabase FileName:="C:\northwind.mdb"

End Sub

4, save the file

Workbook object to save the file using the Save or SaveAs method.
Save method is simple to use, the syntax is
expression.Save, expression is a Workbook object.
Such as: ActiveWorkbook.Save
is saved active workbook.

If this is the first time you save the workbook or to save as, use the SaveAs method to specify a file name for the file.
The syntax is:
expression.SaveAs (FileName, the FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, the AccessMode, ConflictResolution, AddToMru, TextCodepage, The TextVisualLayout, Local)

Meaning specific parameters can be found in the VBA Help, are relatively simple to use.
Example
This example creates a workbook, prompts the user to enter a file name, and then save the workbook.

Set NewBook = Workbooks.Add
Do
    fName = Application.GetSaveAsFilename
Loop Until fName <> False
NewBook.SaveAs Filename:=fName

Application.GetSaveAsFilename to bring up the standard "Save As" dialog box to get user file name, but does not really save any file, and then use the code to save the file. There Application.GetOpenFileName brings up the standard "Open" dialog box.

5, close the file

Close the file can be used or the Close method Workbook Workbooks collection object. The former is to close all open workbooks, which shut down specific workbook.
Close method Grammar Workbook object to:
expression.Close (the SaveChanges, Filename, RouteWorkbook)

SaveChanges parameter indicates whether or not to save the changes, many operations do not need to change, and can be set to False to avoid pop-up dialog box prompts to save the changes.
FileName optional. In this file name to save your changes.
RouteWorkbook optional. If you specify no need to transmit the workbook to the next recipient (no routing slip or has been delivered), the parameter is ignored.

Example
This example close Book1.xls, change and abandon all this workbook.

Workbooks ( "BOOK1.XLS") Close SaveChanges :. = False
  
present exemplary close all open workbooks. If you open a workbook has changed, Microsoft Excel will display the dialog box and asks whether to save changes prompted.

Workbooks.Close

6, integrated example

If F disk has an Excel file test.xls, now have another Excel file to be accessed test.xls data, we look at how to do this using VBA code. Code is as follows:
Public Sub Test ()
the Application.ScreenUpdating = False
the Workbooks.Open "F: \ Test.xls"
ThisWorkbook.Sheets (. 1) .Range ( "B1") ActiveWorkbook.Sheets = (. 1) .Range ( "A2" )
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Sub
first, turn off the screen refresh is to prevent test.xls be seen (and sometimes still see the see) when opened. After opening, the cell value test.xls see Sheet1 A2 assigned in the current workbook Sheet1 cell B2, then close test.xls.
When the workbook is uncertain to be opened, the user can make their choice by calling the Open dialog box.
Can be read as follows:
Public Sub Test ()
the Application.ScreenUpdating = False
Dim AS String Filename
Filename = Application.GetOpenFilename
the Workbooks.Open Filename
ThisWorkbook.Sheets (. 1) .Range ( "B1") ActiveWorkbook.Sheets = (. 1).
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Sub

7. Conclusions

Using Excel object method file operation is the easiest, most convenient, suitable for beginners. For Excel file format, if we merely read the contents of its table, this is the preferred method. For manipulate text files, use the second method is more convenient, To convert text to a table, then the use of this method is also suitable.

Guess you like

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