|
3.9. Respond to XML EventsThe Workbook object provides events that occur before and after data is imported or exported through an XML map. You can use these events to control how the import/export occurs, respond to errors, or cancel the operation. 3.9.1. How to do itFor example, the following event procedures display information about import and export actions as they occur: Private Sub Workbook_BeforeXmlImport(ByVal Map As XmlMap, _ ByVal Url As String, ByVal IsRefresh As Boolean, Cancel As Boolean) Debug.Print "BeforeImport", Map, Url, IsRefresh, Cancel End Sub Private Sub Workbook_BeforeXmlExport(ByVal Map As XmlMap, _ ByVal Url As String, Cancel As Boolean) Debug.Print "BeforeExport", Map, Url, IsRefresh, Cancel End Sub Private Sub Workbook_AfterXmlImport(ByVal Map As XmlMap, _ ByVal IsRefresh As Boolean, ByVal Result As XlXmlImportResult) Debug.Print "AfterImport", Map, Url, Result End Sub Private Sub Workbook_AfterXmlExport(ByVal Map As XmlMap, _ ByVal Url As String, ByVal Result As XlXmlExportResult) Debug.Print "AfterExport", Map, Url, Result End Sub To cancel an import or export action, set the event's Cancel argument to True. The following code allows the user to cancel refreshing or importing data from the Orders_Map: Private Sub Workbook_BeforeXmlImport(ByVal Map As XmlMap, _ ByVal Url As String, ByVal IsRefresh As Boolean, Cancel As Boolean) If Map.name = "Orders_Map" And Not IsRefresh Then res = MsgBox("This action will replace all the data " & _ "in this list. Do you want to continue?", vbYesNo, "Import XML") If res = vbNo Then Cancel = True End If End Sub 3.9.2. How it worksIf the import or export action is caused by code, setting Cancel to True causes an "Operation cancelled by user" error to occur. You should trap for this error if you allow Cancel to be set. For example, the following code handles the potential error when importing data: ' If user cancels, handle error. On Error Resume Next ' Import data. xmap.Import ThisWorkbook.path & "\SimpleOrder.xml" If Err = 1004 Then Debug.Print "User cancelled import." On Error GoTo 0 |
|