access 2007 vba bible phần 6 pps

72 300 0
access 2007 vba bible phần 6 pps

Đ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

Case 1 HTML DoCmd.TransferText transfertype:=acImportHTML, _ TableName:=strTable, _ FileName:=strHTMLXMLFileAndPath, _ hasfieldnames:=True Assign the appropriate form as the subform’s source object. Me![subNewJobs].SourceObject = “fsubNewJobs” Case 2 XML ImportXML DataSource:=strHTMLXMLFileAndPath, _ importoptions:=acStructureAndData DoCmd.SetWarnings False There is no argument for specifying the name of the table that is created when an XML file is imported; it comes in as the name stored in the XML file (usually the XML file name), possibly with a number added on. DoCmd.Rename newname:=strTable, objecttype:=acTable, _ oldname:=strHTMLXMLFile Assign the appropriate form as the subform’s source object. Me![subNewJobs].SourceObject = “fsubNewJobs” End Select ErrorHandlerExit: Exit Sub ErrorHandler: MsgBox “Error No: “ & Err.Number _ & “; Description: “ & Err.Description Resume ErrorHandlerExit End Sub Exporting HTML and XML Files If you want to experiment with exporting Access data to HTML or XML files, try the Export Job Data to HTML or XML File form. If you select the “Export HTML or XML Data” option on the main menu (see Figure 10.10) and click the button to its left, the Export Job Data to HTML or 341 Working with External Data 10 15_047026 ch10.qxp 4/2/07 9:52 PM Page 341 XML File (frmExportHTMLXMLData) form will open (as shown in Figure 10.26). The form has From Date and To Date textboxes for specifying a date range; clicking the “Inspect New Jobs to Export” button loads the subform with the records from the selected date range. FIGURE 10.26 Inspecting the filtered job records to export to an HTML or XML file. Clicking the “Export Jobs to HTML File” button (or “Export Jobs to XML File”; the caption changes with the selection in the “Export File Type” option group) starts the export. The HTML export is done with the TransferText method with the acExportHTML value for the TransferType argu- ment; the XML export is done with the ExportXML method of the Access Application object. Figure 10.27 shows an exported HTML file opened in Internet Explorer 7. Unfortunately, it is com- pletely unformatted and thus probably won’t be very useful. 342 Writing VBA Code to Exchange Data between Office Components Part II 15_047026 ch10.qxp 4/2/07 9:52 PM Page 342 FIGURE 10.27 An exported HTML file opened in Internet Explorer. The code for clearing old data and inspecting the jobs to export is similar to the code for other export types; only the event procedure for the “Export Jobs to HTML/XML File” button is listed as follows; it uses a Select Case statement to export the data to either an HTML file (using the TransferText method) or an XML file, using the ExportXML method of the Access Application object: Private Sub cmdExportJobs_Click() On Error GoTo ErrorHandler Dim intFileType As Integer Dim strQuery As String Dim strTitle As String Dim strPrompt As String Dim strOutputPath As String Dim strFileName As String Dim strFileNameAndPath As String intFileType = Nz(Me![fraFileType].Value, 1) strQuery = “qryFilteredJobs” 343 Working with External Data 10 15_047026 ch10.qxp 4/2/07 9:52 PM Page 343 strOutputPath = GetOutputDocsPath() Select Case intFileType Case 1 HTML strFileName = “Jobs.htm” strFileNameAndPath = strOutputPath & strFileName DoCmd.TransferText transfertype:=acExportHTML, _ TableName:=strQuery, _ FileName:=strFileNameAndPath, _ hasfieldnames:=True Case 2 XML strFileName = “Jobs.xml” strFileNameAndPath = strOutputPath & strFileName ExportXML objecttype:=acExportQuery, _ DataSource:=strQuery, _ datatarget:=strFileNameAndPath End Select strTitle = “Exported jobs” strPrompt = “Exported filtered jobs to “ & strFileNameAndPath MsgBox strPrompt, vbInformation + vbOKOnly, strTitle ErrorHandlerExit: Exit Sub ErrorHandler: MsgBox “Error No: “ & Err.Number _ & “; Description: “ & Err.Description Resume ErrorHandlerExit End Sub If you open an XML file in IE 7, running on Windows Vista, you’ll see a yellow bar with a security warning. If you click the bar you can select to allow blocked content, as shown in Figure 10.28. 344 Writing VBA Code to Exchange Data between Office Components Part II 15_047026 ch10.qxp 4/2/07 9:52 PM Page 344 FIGURE 10.28 A security warning when opening an XML file in Windows Vista. If you select to allow blocked content, you’ll get another security warning, shown in Figure 10.29. Finally, the XML file displays (see Figure 10.30), but as source code, not a properly formatted doc- ument, so it (like the HTML file) is not very useful. FIGURE 10.29 Another Vista security warning. 345 Working with External Data 10 15_047026 ch10.qxp 4/2/07 9:52 PM Page 345 FIGURE 10.30 An XML file opened in Internet Explorer. You can also open an XML file in Excel. After selecting it, you get an Open XML dialog with three options, as shown in Figure 10.31. To see what the formatted XML data looks like, select the “As an XML table” option. FIGURE 10.31 Three options for opening an XML file in Excel. 346 Writing VBA Code to Exchange Data between Office Components Part II 15_047026 ch10.qxp 4/2/07 9:52 PM Page 346 If you accept the default option of “As an XML table,” you’ll get the message shown in Figure 10.32. FIGURE 10.32 Creating an XML schema when opening an XML file in Excel. After accepting this message, the XML file finally opens in Excel, as shown in 10.33, with an extra column called “generated” indicating the time the file was created. FIGURE 10.33 An XML file opened in Excel. If you want to export data from Access to Excel, I recommend using the worksheet or comma-delimited format instead of XML; they are much easier to work with, and support older versions of Excel that can’t open XML files. You can also use the Save method of an ADO recordset with the adPersistXML named constant as the value of its PersistFormat argument, to produce an XML file, but a file produced using this method also opens as source code. NOTE NOTE NOTE NOTE 347 Working with External Data 10 15_047026 ch10.qxp 4/2/07 9:52 PM Page 347 Emailing Exported Text Files Once you have created text files from your Access data, you might want to email them to others who need to review the data. Clicking the “Send Job Lists to Contacts” button opens a form (shown in Figure 10-34) where you can select multiple contacts, and a job file (either .csv or .txt) to send as an attachment to the selected contacts. The figure also shows three email messages with the selected job file attachment. FIGURE 10.34 A form for selecting contacts and a job file to email to them, with three email messages created from the form. The cmdMergetoEMailMulti_Click event procedure is listed below: Private Sub cmdMergetoEMailMulti_Click() On Error GoTo ErrorHandler Dim strJobFile As String Set lst = Me![lstSelectContacts] 348 Writing VBA Code to Exchange Data between Office Components Part II 15_047026 ch10.qxp 4/2/07 9:52 PM Page 348 Check that at least one contact has been selected. If lst.ItemsSelected.Count = 0 Then MsgBox “Please select at least one contact” lst.SetFocus GoTo ErrorHandlerExit End If Test for required fields. strSubject = Me![txtSubject].Value If strSubject = “” Then MsgBox “Please enter a subject” Me![txtSubject].SetFocus GoTo ErrorHandlerExit End If strBody = Me![txtBody].Value If strBody = “” Then MsgBox “Please enter a message body” Me![txtBody].SetFocus GoTo ErrorHandlerExit End If For Each varItem In lst.ItemsSelected Check for email address. strEMailRecipient = Nz(lst.Column(1, varItem)) Debug.Print “EMail address: “ & strEMailRecipient If strEMailRecipient = “” Then GoTo NextContact End If strJobFile = Nz(Me![txtJobFile]) Create a new mail message with the job file attachment and send to contact. Set appOutlook = GetObject(, “Outlook.Application”) Set msg = appOutlook.CreateItem(olMailItem) With msg .To = strEMailRecipient .Subject = strSubject .Body = strBody If strJobFile <> “” Then .Attachments.Add strJobFile End If .Display End With 349 Working with External Data 10 15_047026 ch10.qxp 4/2/07 9:52 PM Page 349 NextContact: Next varItem ErrorHandlerExit: Set appOutlook = Nothing Exit Sub ErrorHandler: Outlook is not running; open Outlook with CreateObject. If Err.Number = 429 Then Set appOutlook = CreateObject(“Outlook.Application”) Resume Next Else MsgBox “Error No: “ & Err.Number _ & “; Description: “ & Err.Description Resume ErrorHandlerExit End If End Sub You may have contacts that have only an email address, or a phrase like “Tech. Support” entered as the last name, or contacts with just a first name, or a whole name entered into the LastName field, or sets of contacts who work for the same company, where the company name is entered differently on different contact records. Importing from such contacts can cause problems, such as creating multiple Company records with variations of a company name. I am planning to upgrade the Synchronizing Contacts database to deal with various types of problem data, and to add some new features; look for an updated version of the database on my Web site, http://www.helenfeddema.com. Summary This chapter dealt with exporting to, and importing from, a variety of file formats, ranging from the oldest formats to those so new that they are scarcely useful yet. Text files, both comma-delimited and fixed-width (columnar), have been used for data export and import since the earliest days of computers, and they are still very useful, especially the comma-delimited file format. Files exported to this format can be imported by a great many applications, which makes it very useful for exporting data that is to be imported by an application not directly supported as an Access export type. The reverse is also true: many applications can export their data to a fixed-width or comma-delimited file, from which they can be imported into Access tables. If you have data in ancient dBASE, Paradox, or Lotus files, Access offers options for importing from these files, so you can get your old data into Access tables. Although it isn’t likely to be required these days, you can also export data from Access tables to these legacy formats. And finally, the new HTML and XML formats are supported — but not very well. These import and export types still have little utility for importing data into Access tables, either because they simply don’t work or because they aren’t really relevant. Hopefully, these file formats will be better sup- ported for Access import and export in future versions of Office. NOTE NOTE 350 Writing VBA Code to Exchange Data between Office Components Part II 15_047026 ch10.qxp 4/2/07 9:52 PM Page 350 [...]... to Access Outlook and Access contacts are different Modify Access contact to match Outlook contact Modify Outlook contact to match Access contact Go to next contact record Mark contact for deletion Copy all Access contacts to Outlook Copy all Outlook contacts to Access No Outlook contact Create new Outlook contact to match Access contact Go to next contact record Mark contact for deletion Copy all Access. .. to Access No Access contact Create new Access contact to match Outlook contact Go to next contact record Mark contact for deletion Copy all Access contacts to Outlook Copy all Outlook contacts to Access 375 11 Part II Writing VBA Code to Exchange Data between Office Components To copy data in one field, rather than updating an entire contact record, select either Access to Outlook” or “Outlook to Access ... when synchronizing the Access and Outlook contacts This dialog is shown in Figure 11.9 360 Synchronizing Access and Outlook Contacts FIGURE 11.9 An Outlook Select Folder dialog for selecting the Contacts folder for synchronizing Re-creating the Flat-file Tables of Access and Outlook Data If you have recently entered new contact data or modified existing contact records, either in Access or Outlook, click... “Working with Outlook Contacts” section in Chapter 8 for information on exchanging data between a single Access contacts table and Outlook contacts CROSS-REF 351 IN THIS CHAPTER Updating Outlook contacts from Access, and vice versa Copying attachments from Outlook to Access, and vice versa Part II Writing VBA Code to Exchange Data between Office Components Creating a Denormalized Table from a Set of Linked... II Writing VBA Code to Exchange Data between Office Components FIGURE 11.4 The Company Info tab of the Company and Contact Information form Figure 11.5 shows the Contact Info tab, with a Contact IDs and Phones subform 3 56 Synchronizing Access and Outlook Contacts FIGURE 11.5 The Contact Info tab of the Company and Contact Information form The sample database’s main menu (shown in Figure 11 .6) has a command...Synchronizing Access and Outlook Contacts F or a long time — really, since Office 97, when Outlook was introduced — I have wanted to write VBA code to synchronize Access contacts with Outlook contacts My Access contacts are stored in a set of linked tables, with companies linked to contacts and contacts linked... rstSourceAttachments.RecordCount > 0 Then Set rstTargetAttachments = _ rstTarget![Attachments].Value Call CopyAccessAttsToAccess(rstSourceAttachments, _ rstTargetAttachments) Else rstSourceAttachments.Close End If rstTarget![LastUpdated] = Nz(rstSource!LastUpdated) rstTarget.Update rstSource.MoveNext Loop rstSource.Close 367 11 Part II Writing VBA Code to Exchange Data between Office Components The next source object is qryContactIDsPhones... (tblOutlookContacts and tblAccessContacts) have matching fields; they are displayed in subforms on the two forms used for comparing Access and Outlook contact data Figure 11.12 shows the form that compares contacts by Contact ID (frmCompareContactsByID), with data from an Access contact on the left and the matching Outlook contact (if there is one) on the right FIGURE 11.12 A form that compares Outlook and Access contacts... whether the Outlook and Access contacts are identical, different, or one is missing, as shown in Table 11.1 374 Synchronizing Access and Outlook Contacts FIGURE 11.14 Selecting a contact by Contact ID TABLE 11.1 Contact Match Status and Actions to Select Contact Status Available Actions Outlook and Access contacts are identical Go to next contact record Mark contact for deletion Copy all Access contacts to... simply import data from Outlook to an Access table, or export data from an Access table to Outlook contacts, if the Access contacts are a set of linked tables, as they should be, the task is much more difficult — but not impossible Live linking is out of the question, because of the difference in structure between a folder of Outlook contacts and a set of linked Access tables, but the contacts can be . CHAPTER Updating Outlook contacts from Access, and vice versa Copying attachments from Outlook to Access, and vice versa Synchronizing Access and Outlook Contacts 16_ 0470 26 ch11.qxp 4/2/07 9:52 PM Page. with a Contact IDs and Phones subform. 3 56 Writing VBA Code to Exchange Data between Office Components Part II 16_ 0470 26 ch11.qxp 4/2/07 9:52 PM Page 3 56 FIGURE 11.5 The Contact Info tab of the. copying attachments from an Access table record to an Outlook contact or vice versa. 357 Synchronizing Access and Outlook Contacts 11 16_ 0470 26 ch11.qxp 4/2/07 9:52 PM Page 357 FIGURE 11 .6 The main menu

Ngày đăng: 14/08/2014, 06:22

Từ khóa liên quan

Mục lục

  • Access 2007 VBA Bible

    • Part II: Writing VBA Code to Exchange Data between Office Components

      • Chapter 10: Working with External Data

        • Emailing Exported Text Files

        • Summary

        • Chapter 11: Synchronizing Access and Outlook Contacts

          • Creating a Denormalized Table from a Set of Linked Tables

          • Comparing Outlook and Access Contacts

          • Working with Attachments

          • Summary

          • Chapter 12: Going Beyond the Basics

            • Creating Fancy Word Shipping Labels

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

Tài liệu liên quan