Microsoft Excel VBA Programming for the Absolute Beginner Second Edition phần 8 doc

50 609 0
Microsoft Excel VBA Programming for the Absolute Beginner Second Edition phần 8 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

will be asked if you want to open the file as an XML list, read-only workbook, or to use the XML Source Task Pane (see Figure 8.3). Typically, you load the data into a worksheet as an Excel list in order to take advantage of the data management features a list provides. If the XML file does not reference an existing schema document (.xsd file extension), Excel will automatically create one (you may be notified of this fact as shown in Figure 8.4) and store it internally with the workbook. You don’t have to see the schema, or know how it describes your XML document, but you should know that it’s there working in the back- ground defining your data elements for Excel. When you open an XML file as a list, Excel adds the data to a worksheet and creates a list (normally created from the Data menu). An Excel list provides additional features and for- matting that makes it easy to identify and modify the list. Figure 8.5 shows data from an XML document that describes a list of words and topics (something you might use in the project for Chapter 7). The list is highlighted with a blue border, and a filter (normally selected from the Data menu) is automatically applied. In addition, an asterisk marks the next available row for inserting data into the list. The following XML code defines the basic structure of the XML file opened in Figure 8.5—the data was omitted for brevity. <?xml version=”1.0” encoding=”UTF-8”?> <word_find> <topic_word_pair> <topic></topic> <word></word> </topic_word_pair> <!—repeat topic_word_pair element—> </word_find> 339 Chapter 8 • Using XML with Excel-VBA Projects Figure 8.3 Selecting the data format when opening an XML file. Figure 8.4 Opening an XML file with no referenced schema. 340 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 8.5 Opening an XML file as a list. You can manage the list and the data it contains from the XML selection on the Data menu and/or the Source Task Pane (see Figures 8.6 and 8.7). For example, you can export changes to the list to the XML file, refresh the data in the list, edit the properties of the XML map, and more. As you will see shortly, Excel provides several objects that allow your VBA pro- grams to accomplish these same tasks. AutoFilter List border Insert row Figure 8.6 The XML menu selection in Excel. Excel also uses the provided (or created) XML schema to create an XML map that serves to map the elements in the XML file to specific ranges in the worksheet. The map, shown in the Source Task Pane in Figure 8.7, was created automatically when I opened the XML file. The topicID element is mapped to the range A1:A23 in the worksheet and word is mapped to B1:B23. The map tells Excel how changes to the list must be saved in the XML file such that it preserves its original structure. You can also import data from an XML file into any existing worksheet by selecting Data, XML, Import (see Figure 8.6) from the application window. Again, a schema will be auto- matically created (if one is not referenced) and you will be prompted to select a range in the worksheet telling where you want the data inserted. Saving Worksheets to XML Files Saving existing data from a worksheet to an XML file is easy. Select File, Save As from the application window and choose one of two possibilities for XML file types from the Save As dialog box as shown in Figure 8.8. 341 Chapter 8 • Using XML with Excel-VBA Projects Figure 8.7 The XML Source Task Pane. 342 Saving Data as an XML Spreadsheet If you choose to save the data as an XML spreadsheet, Excel will use its own schema to define the document. As you might expect, the XML required to define a spreadsheet is quite long, but you don’t have to worry about that because Excel creates it for you. The root tag is <Workbook> and it will contain nested <Worksheet> tags for every worksheet in a workbook. In addition to the <Worksheet> tags, there are several other tags that describe the formatting and objects in the workbook. The following code shows the basic format of a document saved using the Excel-XML structure (data and attributes have been deleted for brevity and clarity). <Workbook> <DocumentProperties/> <OfficeDocumentSettings/> <ExcelWorkbook/> <Styles> <Style/> </Styles> <Names> <NamedRange”/> </Names> <Worksheet> <Table> <Column> <Row> <Cell> <Data/> Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 8.8 Excel’s Save As dialog. Save as an XML spreadsheet Save as XML data </Cell> </Row> </Table> <WorksheetOptions/> </Worksheet> </Workbook> The document resulting from saving a workbook with the Excel-XML structure is just a text file; however, it is also an XML file defined using the Excel-XML schema. As a well-formed and schema-defined XML document, it can be opened by other applications that support XML such that the formatting and other elements of the spreadsheet (for example, formu- las) are preserved. Unfortunately, Excel cannot save objects such as autoshapes and charts in an Excel workbook to an XML document. Saving a Worksheet as XML Data Saving data in a worksheet to an XML document without following the Excel-XML schema is a bit more complicated. In fact, you can’t save worksheet data to a new XML file using the file type XML Data (see Figure 8.8) unless it has first been mapped to an existing schema. The easiest way to save data to a new XML file without using the Excel-XML format is to first open or import an existing XML file with the desired structure as a list into a worksheet. The XML file doesn’t even need data, just the required tags. After opening the XML file and editing the data in Excel, you can simply save it as a new XML file using the map created by Excel when you first opened or imported the file. XML and VBA The XML object model may still be evolving, but the Excel 2003 object model is reasonably robust with regard to XML support. There are several methods of the Workbook object that can be used to import and export XML data. Furthermore, the XmlMaps object has been added to the object hierarchy to provide more methods for data management. Saving and Opening XML Documents To save a workbook as an XML document use the SaveAs() method of the Workbook object. The following example saves the workbook as an XML document with the name myFile.xml using two named arguments (Filename and FileFormat) with the SaveAs() method. ActiveWorkbook.SaveAs Filename:= “myFile.xml”, FileFormat:=xlXMLSpreadsheet The constant xlXMLSpreadsheet assigned to the FileFormat argument specifies the Excel-XML format. 343 Chapter 8 • Using XML with Excel-VBA Projects 344 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition To open an XML document previously saved with the Excel-XML structure use either the Open() or OpenXML() methods of the Workbooks collection object. Workbooks.Open Filename:= “myFile.xml” If the structure of the XML document is Excel-XML, then the opened file will conform to that of a normal Excel spreadsheet; however, if the file is just a well-formed XML document (not structured as Excel-XML), then Excel will open it as tabular data. Figure 8.9 shows the result of opening the words.xml file with the Open() method of the Workbooks collection object. The words.xml file had not been previously saved using the Excel-XML structure. The OpenXML() method of the Workbooks collection object includes an optional argument ( LoadOption) that allows you to choose how to open the XML file. VBA-defined constants you can use with the LoadOption argument include: xlXmlLoadImportToList, xlXmlLoadOpenXml, xlXmlLoadMapXml, and xlXmlLoadPromptUser. To import the document as a list, use xlXml- LoadImportToList ; otherwise xlXmlLoadOpenXml will open the document in tabular form. Using the constant xlXmlLoadMapXml will display the schema-map of the XML document file in the XML Source Task Pane, but will not import any data into the worksheet. Finally, the constant xlXmlLoadPromptUser displays a prompt (see Figure 8.3) to the user so he or she can choose how to open the file. Workbooks.OpenXML Filename:= “myFile.xml”, LoadOption:=xlXmlLoadImportToList Figure 8.9 An XML file opened in tabular form. The XmlMap Object When you open an XML file, either programmatically or through the application interface, Excel automatically creates an XML map. An XML map is represented in VBA by the XmlMap object. An XML map serves to map the elements and attributes of an XML file to worksheet ranges. For example, the XML map named word_find_Map in Figure 8.7 maps the range A1:A23 to the <topic> element in the words.xml document and the range B1:B23 to the <word> element. Each XmlMap object is contained in an XmlMaps collection object which is returned from the Workbook object via the XmlMaps property. The following code loops through the XmlMaps col- lection in the active workbook and prints the names of all XmlMap objects in the active work- book to the Immediate window. Dim maps As XmlMaps Dim myMap As xmlMap Set maps = ActiveWorkbook.XmlMaps For Each myMap In maps Debug.Print myMap.Name Next The XmlMap object includes four methods for importing and exporting data between an XML file or string variable, and worksheet ranges mapped to the object. Use the Import() and Export() methods of the XmlMap object to import and export data between an XML file and mapped ranges on a worksheet. The following example first imports data from the XML file called words.xml using an existing XmlMap object in the active workbook and then exports the same data to the file words2.xml. The file words2.xml is created if it doesn’t already exist. Dim filePath As String, filePath2 As String filePath = ActiveWorkbook.Path & “\words.xml” filePath2 = ActiveWorkbook.Path & “\words2.xml” ActiveWorkbook.XmlMaps(1).Import URL:=filePath, Overwrite:=True ActiveWorkbook.XmlMaps(1).Export URL:=filePath2, Overwrite:=True The URL argument of the Import() and Export() methods is a string that specifies a file’s path. When the Overwrite argument is true, the data is overwritten in the worksheet cells or the file, depending if you are importing or exporting data, respectively. At least one XmlMap object (note the index value used with the XmlMaps property) must already exist in the active workbook, or the previous code listing will fail to execute. Furthermore, the XmlMap object should be compatible with the structure of the XML file words.xml, or the data will not be properly mapped to the appropriate ranges in the worksheet. Presumably, you can 345 Chapter 8 • Using XML with Excel-VBA Projects 346 create the XmlMap object from a compatible file by opening it in the Excel application prior to invoking these methods, so this shouldn’t present a problem. To copy data between a string variable and a mapped range on a worksheet, use the ImportXml() and ExportXml() methods of the XmlMap object. The following example exports data mapped with the XmlMap object named word_find_Map to the string variable xmlStr. The ExportXml() method returns an XlXmlExportResult constant (xlXmlExportSuccess or xlXmlExportValidationFailed) indicating the result of the data export. The names of the con- stants are self-explanatory. Dim xmlStr As String If ActiveWorkbook.XmlMaps(“word_find_Map”).ExportXml(Data:=xmlStr) <> xlXmlExportSuccess Then MsgBox “Export failed” End If Similarly, to copy data from the string variable xmlStr to the cells mapped by the XmlMap object named word_find_Map, I use the ImportXml() method of the XmlMap object. The content of the variable xmlStr must be structured as a well-formed XML document. If ActiveWorkbook.XmlMaps(“word_find_Map”).ImportXml(xmlData:=xmlStr) <> xlXmlImportSuccess Then MsgBox “Import failed” End If The ImportXML() method returns an XlXmlImportResult constant that I have used to test for a successful import (the remaining two constants are xlXmlImportElementsTruncated and xlXmlImportValidationFailed). There are several properties associated with the XmlMap object. Most notable are the Name, DataBinding, IsExportable, RootElementName, and Schemas properties. The DataBinding prop- erty returns an XmlDataBinding object. The XmlDataBinding object represents the connection between the data source (XML file) and the XmlMap object. The Refresh() method of the XmlDataBinding object quickly refreshes the mapped cells with the data from the XML file. ActiveWorkbook.XmlMaps(“word_find_Map”).DataBinding.Refresh The IsExportable property of the XmlMap object returns a Boolean value indicating whether or not Excel can export the mapped data. Potential reasons that an export would fail include: file path error, improper mappings, or incompatibilities with the schema. The Schemas property returns an XMLSchemas collection object contained by an XmlMap object. Typically, there is only one XmlSchema object per XmlMap object; so specifying an index value Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition of 1 with the Schemas property returns the desired XmlSchema object. The XmlSchema object rep- resents the schema that defines the mapped XML document. The following code listing first exports mapped data to a file called words3.xml before out- putting the value of a few properties of an XmlMap object to the Immediate window. The XmlMap object was created from the words.xml file whose structure was listed earlier in this chapter. Dim myMap As XmlMap Dim filePath As String filePath = ActiveWorkbook.Path & “\ words3.xml” Set myMap = ActiveWorkbook.XmlMaps(“word_find_Map”) With myMap If .IsExportable Then .Export URL:=filePath, Overwrite:=True Else MsgBox “Not exportable” End If Debug.Print .Name Debug.Print .RootElementName Debug.Print .Schemas(1).XML End With The XML property of the XmlSchema object (returned by the Schemas property of the XmlMap object) returns a string representing the schema used in the mapping; thus, it is an excel- lent method for collecting a schema for an existing XML file. Unfortunately, the XML prop- erty returns the string without white space so you have to add the line feeds and indentation to make the text well-formed. Other methods of the Workbook object you can use to save or import XML data include: SaveAsXmlData(), XmlImport(), and XmlImportXml(). The SaveAsXmlData() method exports mapped data to an XML document file. It requires two arguments— Filename and Map—that are used to specify a name for the XML file and the XmlMap object representing the mapped data. Dim myMap As XmlMap Dim filePath As String Set myMap = ActiveWorkbook.XmlMaps(1) filePath = ActiveWorkbook.Path & “\test.xml” ActiveWorkbook.SaveAsXMLData Filename:=filePath, Map:=myMap 347 Chapter 8 • Using XML with Excel-VBA Projects 348 The XmlImport() and XmlImportXml() methods import data from an XML file and data stream (string variable), respectively. Both methods require a data source (XML file or string variable) and an XmlMap object. The arguments Overwrite and Destination are optional, but Destination must be omitted if the XmlMap object has already been loaded into the workbook. This makes sense because once an XmlMap object has been created, the data is mapped to specific ranges in the worksheet and cannot be changed. The following code imports XML data from the file sample.xml to a mapped range on the active worksheet using an existing XmlMap object ( sample_Map). Dim myMap As XmlMap Dim filePath As String filePath = ActiveWorkbook.Path & “\sample.xml” Set myMap = ActiveWorkbook.XmlMaps(“sample_Map”) ActiveWorkbook.XmlImport URL:=filePath, ImportMap:=myMap, Overwrite:=True The XmlImport() method imports data from an XML file whereas the XmlImportXml() method imports XML data from a string variable. The data stored in the string variable ( xmlStr in the following example) must be that of a well-formed XML document and is assigned to the Data argument of the XmlImportXml() method. ActiveWorkbook.XmlImportXml Data:=xmlStr, ImportMap:=myMap2, Overwrite:=True The ListObject Object As discussed earlier, when you import XML data into a worksheet you have the choice to insert the data as an Excel list. When adding XML data to a list, Excel creates a ListObject object to represent the list. The ListObject object is subordinate to the Worksheet object; therefore, all ListObject objects added to a worksheet are returned as a collection via the ListObjects properties of the Worksheet object. Individual ListObject objects can be accessed from the ListObjects collection. Dim lstObjects as ListObjects Dim lstObject As ListObject Set lstObjects = ActiveSheet.ListObjects Set lstObject = lstObjects(1) Each XML data set that has been mapped to a list is represented by a ListObject object. The ListObject object provides an easy path to the range of cells mapped to an XML document. Use the Range property of the ListObject object to return the Range object representing these mapped cells. To return the range representing the insert row for a list (that’s the row with Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition [...]... just before the xml file extension 3 58 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition When a worksheet already contains an Excel list mapped to an XML document file, you can use the XmlMap object to export the current data from the list to the file This is exactly what I’ve done here I set the XmlMap object variable to its corresponding XML map in the worksheet using the name... window and the advantages of adding the data to an Excel list Finally, you learned how to use several new objects in the Excel object model designed to support XML This included 374 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition the XmlMap object and the ListObject object and some of their associated and/or subordinate objects For the chapter project, you revisited the Math... stored in memory, and then written to a worksheet at the end of the game— potentially the only data saved by the program (but only if the user so desired) The new 350 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition version of the Math Game automatically stores the program’s data (tests, student names, and test results) in XML files I added worksheet interfaces for writing tests,... Worksheets(“Students”).ListObjects(“Students”) For I = 2 To studList.Range.Rows.Count MathGameSheet.cmbStudents.AddItem studList.Range.Cells(I, 1).Value Next I End Sub 364 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Taking a Test A majority of the code for the Math Game program is still located in the same worksheet module as the original program from Chapter 4 Once the test begins, the algorithm is pretty much the. .. the test properties data from the XML file to the cells in the list The XmlImport() method of the Workbook object imports the data from the XML document file It is worth reiterating that the XML document file structure must match the existing XML map structure in the workbook If the two structures do not match, Excel ignores the command Chapter 8 • Using XML with Excel- VBA Projects 361 Public Sub OpenXMLFile(fileName... be found in the XML declaration at the beginning of the document CK Excel adds the standalone document declaration so that it knows the XML document has external markup declarations (the schema created by Excel) , but these external declarations do not affect the document’s content In addition to the standalone document declaration, Excel adds a... data source for the Combo Box control on the Math Game worksheet 12 The user shall be allowed to view the test results for all students 13 The results worksheet shall be formatted with an XML map and Excel list to link the data in the worksheet to the file containing the results 14 The results worksheet and the XML file containing the results shall be updated at the completion of each test 15 The user... ListObject For Each lo In ActiveSheet.ListObjects If lo.Name = “List1” Then lo.Name = “Problems” End If Next End Sub This gives a meaningful name to the ListObject object that I can reference in my program to make it more self-documenting 366 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Setting the MoveAfterReturn property of the Application object to false ensures that the answer... property fails—generating a runtime error Data in the list is deleted using the Delete() method of the Range object and shifting cells up Note that I do not update the XML document file after clearing the range It’s not necessary since it will be updated with the next completed test 362 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Option Explicit Private Sub cmdResetResults_Click()... where it is passed to the OpenXMLFile() procedure The Open dialog is shown in Figure 8. 13 Private Function GetXmlFile() As String Dim fileDiag As FileDialog Dim fPath As String fPath = ActiveWorkbook.path & “\TestProperties\” 360 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition ‘——————————————————‘Configure and show the open dialog ‘Open the file selected by the user ‘——————————————————Set . assigned to the FileFormat argument specifies the Excel- XML format. 343 Chapter 8 • Using XML with Excel- VBA Projects 344 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition To. return the range representing the insert row for a list (that’s the row with Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition the asterisk, see Figure 8. 5), use the InsertRowRange. to the data in columns I through K via the XML map named results_Map. Because the file stores all test Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Figure 8. 12 The

Ngày đăng: 12/08/2014, 16:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan