Access 2007 VBA Programmer’s Reference phần 6 pptx

115 474 0
Access 2007 VBA Programmer’s Reference phần 6 pptx

Đ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

The following code does the same thing for the Having clause: ‘ find length of HAVING portion If intStartHAVING > 0 Then ‘ start with longest it could be intLenHAVING = intLenSQL -intStartHAVING + 1 If intStartWHERE > 0 And intStartWHERE > intStartHAVING _ And intStartWHERE < intStartHAVING + intLenHAVING Then ‘we found a new portion closer to this one intLenHAVING = intStartWHERE -intStartHAVING End If If intStartORDERBY > 0 And intStartORDERBY > intStartHAVING _ And intStartORDERBY < intStartHAVING + intLenHAVING Then ‘we found a new portion closer to this one intLenHAVING = intStartORDERBY -intStartHAVING End If If intStartGROUPBY > 0 And intStartGROUPBY > intStartHAVING _ And intStartGROUPBY < intStartHAVING + intLenHAVING Then ‘we found a new portion closer to this one intLenHAVING = intStartGROUPBY -intStartHAVING End If End If And this code does the same thing for the Order By clause: ‘ find length of ORDERBY portion If intStartORDERBY > 0 Then ‘ start with longest it could be intLenORDERBY = intLenSQL -intStartORDERBY + 1 If intStartWHERE > 0 And intStartWHERE > intStartORDERBY _ And intStartWHERE < intStartORDERBY + intLenORDERBY Then ‘we found a new portion closer to this one intLenORDERBY = intStartWHERE -intStartORDERBY End If If intStartGROUPBY > 0 And intStartGROUPBY > intStartORDERBY _ And intStartGROUPBY < intStartORDERBY + intLenORDERBY Then ‘we found a new portion closer to this one intLenORDERBY = intStartGROUPBY -intStartORDERBY End If If intStartHAVING > 0 And intStartHAVING > intStartORDERBY _ And intStartHAVING < intStartORDERBY + intLenORDERBY Then 533 Chapter 15: SQL and VBA 47033c15.qxd:WroxProgRef 3/30/07 12:27 AM Page 533 ‘we found a new portion closer to this one intLenORDERBY = intStartHAVING -intStartORDERBY End If End If Finally, the length of the Where clause is determined: ‘ find length of WHERE portion If intStartWHERE > 0 Then ‘ start with longest it could be intLenWHERE = intLenSQL -intStartWHERE + 1 If intStartGROUPBY > 0 And intStartGROUPBY > intStartWHERE _ And intStartGROUPBY < intStartWHERE + intLenWHERE Then ‘we found a new portion closer to this one intLenWHERE = intStartGROUPBY -intStartWHERE End If If intStartORDERBY > 0 And intStartORDERBY > intStartWHERE _ And intStartORDERBY < intStartWHERE + intLenWHERE Then ‘we found a new portion closer to this one intLenWHERE = intStartORDERBY -intStartWHERE End If If intStartHAVING > 0 And intStartHAVING > intStartWHERE _ And intStartHAVING < intStartWHERE + intLenWHERE Then ‘we found a new portion closer to this one intLenWHERE = intStartHAVING -intStartWHERE End If End If Now that all the starting positions and lengths of the five SQL clauses have been determined, the output parameters can be set: ‘ set each output portion If intStartSELECT > 0 Then strSELECT = Mid$(strSQL, intStartSELECT, intLenSELECT) End If If intStartGROUPBY > 0 Then strGROUPBY = Mid$(strSQL, intStartGROUPBY, intLenGROUPBY) End If If intStartHAVING > 0 Then strHAVING = Mid$(strSQL, intStartHAVING, intLenHAVING) End If If intStartORDERBY > 0 Then strOrderBy = Mid$(strSQL, intStartORDERBY, intLenORDERBY) End If If intStartWHERE > 0 Then strWhere = Mid$(strSQL, intStartWHERE, intLenWHERE) End If 534 Chapter 15: SQL and VBA 47033c15.qxd:WroxProgRef 3/30/07 12:27 AM Page 534 Exit_Procedure: Exit Sub Error_Handler: MsgBox (Err.Number & “: “ & Err.Description) Resume Exit_Procedure End Sub The next two functions merely use the ParseSQL procedure to break up the SQL statement into its five clauses, and then they replace the appropriate clause with the new clause that was passed in: Public Function ReplaceWhereClause(strSQL As Variant, strNewWHERE As Variant) On Error GoTo Error_Handler ‘This subroutine accepts a valid SQL string and Where clause, and ‘returns the same SQL statement with the original Where clause (if any) ‘replaced by the passed in Where clause. ‘ ‘INPUT: ‘ strSQL valid SQL string to change ‘OUTPUT: ‘ strNewWHERE New WHERE clause to insert into SQL statement ‘ Dim strSELECT As String, strWhere As String Dim strOrderBy As String, strGROUPBY As String, strHAVING As String Call ParseSQL(strSQL, strSELECT, strWhere, strOrderBy, _ strGROUPBY, strHAVING) ReplaceWhereClause = strSELECT &“”& strNewWHERE &“”_ & strGROUPBY &“”& strHAVING &“”& strOrderBy Exit_Procedure: Exit Function Error_Handler: MsgBox (Err.Number & “: “ & Err.Description) Resume Exit_Procedure End Function Public Function ReplaceOrderByClause(strSQL As Variant, strNewOrderBy As Variant) On Error GoTo Error_Handler ‘ ‘This subroutine accepts a valid SQL string and Where clause, and ‘returns the same SQL statement with the original Where clause (if any) ‘replaced by the passed in Where clause. ‘ ‘INPUT: ‘ strSQL valid SQL string to change ‘OUTPUT: 535 Chapter 15: SQL and VBA 47033c15.qxd:WroxProgRef 3/30/07 12:27 AM Page 535 ‘ strNewOrderBy New OrderBy clause to insert into SQL statement ‘ Dim strSELECT As String, strWhere As String Dim strOrderBy As String, strGROUPBY As String, strHAVING As String Call ParseSQL(strSQL, strSELECT, strWhere, strOrderBy, _ strGROUPBY, strHAVING) ReplaceOrderByClause = strSELECT &“”& strWhere &“”& strNewOrderBy Exit_Procedure: Exit Function Error_Handler: MsgBox (Err.Number & “: “ & Err.Description) Resume Exit_Procedure End Function These SQL handling procedures can be added to all of your Access applications in their own module, such as basSQLTools. By using ReplaceWhereClause and ReplaceOrderByClause, you can take a lot of the hassle out of manipulating SQL strings in your VBA code. Summary VBA and SQL are both powerful tools for you to use in your Access applications, and they work very well together. The techniques explained in this chapter enable you to add instant sorting to column headings, provide easy record selection on continuous forms, build smart cascading combo boxes that change their drop-down lists based on other selections, prompt your user for report selection criteria without using parameter queries, and change the SQL statement inside saved queries. With these fea- tures, your Access applications will be more flexible and easy to use. 536 Chapter 15: SQL and VBA 47033c15.qxd:WroxProgRef 3/30/07 12:27 AM Page 536 Working with Office Applications Designing complete, fully functioning database solutions in Microsoft Access is done quite often without the need for working with any another Microsoft Office application. After all, you can use Access forms to enter data, Access reports to view and print data, and the SendObject method to send Access information via e-mail. On the other hand, it is not only possible, but extremely useful to leverage the features of other Office applications to enhance an Access solution with very few lines of code. For example, you might want to use Outlook to generate a customized e-mail with information from an Access table. If the Access solution offers a method for users to export data to Excel, those users can leverage Excel features to customize data in their own way without unwanted interaction with your application. Exporting data to Microsoft Word gives users the capability to add their own text, perform mail merges, customize documentation, and much more in a practi- cally universal file format. This chapter illustrates methods for employing other Office applica- tions directly in your Access database solution. You’ll use code examples for working with the other Office programs, and take a look at some real-world situations that illustrate how interaction with other Office programs can enhance your application. Please download the sample database code files for this chapter to see the code included in this chapter. Sharing Information Is a Two-Way Street When sharing information between multiple Microsoft Office programs, you can write code two ways: ❑ Write the code within Access to “push” the data into the other Office programs. ❑ Write code within those other programs to “pull” data from Access into them. Because this book is about Access 2007 VBA, most of the discussion covers the push scenario, but don’t worry — there are examples of the pulling data into other applications as well. Many of the 47033c16.qxd:WroxProgRef 3/30/07 12:27 AM Page 537 examples in this chapter are based on a hypothetical Inventory Control application for pallets of material from a manufacturing plant, included in the sample code for this chapter. The sample Inventory Control application is an example of a database solution that allows users to store asset information for their business. A series of forms, reports, tables, and queries enable users to work with the data. In addition, there are a number of more advanced tasks users might want to tap into, which require other components in the Microsoft Office System. Leveraging the other Office 2007 programs, such as Outlook, Word, and Excel, is a powerful way to enhance your Access database application. Working with Outlook In today’s high-tech world, one of the most common forms of communication is e-mail. Allowing users to send e-mail messages via your application that contains customized data provides a powerful feature to any database application. Access 2007 makes it extremely easy and inexpensive to implement this functionality, using just a few lines of VBA code Open the sample database and click the Material Order Form button. The Frame Material Order Form opens. Assume that the current record shown in this form contains important information that the user needs to communicate via an e-mail. Click the Alert button and the new e-mail is created. Notice that the e-mail contains the order number, the original order due date, expected material receipt date, and the required Action information that is contained in the current record in the form. Although this message is fairly simple, it is extremely easy to continue customizing the data to your preference, or better yet, let the user do it herself to add a personal touch. The programmatic creation of e-mails, as found in the Material Orders form in the sample database, is made possible by the Outlook Object Model. To write the VBA code to export the data from Access to Outlook, open the Frame Material Order Form in Design mode and view the code behind the Click event of the Alert button. In working with the Outlook Object Model, you must set a reference to the Microsoft Outlook 12.0 Object Model option in the References dialog box, found under the Tools menu in the Visual Basic Editor. That allows the objects, properties, and methods available in Outlook to be manipulated directly from VBA in the Access application. In the sample database, this reference has already been set in the VBA project and if Outlook 2007 is not installed on the machine, an error describing a missing reference will be shown when the database solution is opened. Following is the code in the Click event of the Alert button. It first declares the required object variables to work with Outlook and a few Outlook objects necessary to set up a new e-mail message. ‘Reference the Outlook Application Dim olApp As Outlook.Application ‘The NameSpace object allows you to reference folders Dim olNS as Outlook.NameSpace Dim olFolder as Outlook.MAPIFolder ‘Create a reference to the email item you will use to send your email Dim olMailItem As Outlook.MailItem 538 Chapter 16: Working with Office Applications 47033c16.qxd:WroxProgRef 3/30/07 12:27 AM Page 538 Next, you create the Outlook.Application object. Any time you need to automate an Office applica- tion, you must create an application object using one of two methods. The first is the CreateObject method, which creates a brand new instance of the application class for COM objects (including Office applications, which are themselves COM objects). The second is GetObject, which gets an existing instance of the object that is already running on the system. In this example, you use the CreateObject method to get an instance of the Outlook.Application object. Outlook is unique among the Microsoft Office applications in that there can be only one instance of Outlook running at any given time. If CreateObject is called for an Outlook.Application object and Outlook is already running, the application is smart enough to return the current instance of the Outlook program. If it is not already running, Outlook will be invoked. Call the CreateObject method to create the Outlook application. Then, add some code to reference the NameSpace object, setting a reference to the Inbox folder, and adding a new e-mail message (IPM.Note) to your code: Set olApp = CreateObject(“Outlook.Application”) Set olNS = olApp.GetNamespace(“MAPI”) Set olFolder = olNS.GetDefaultFolder(olFolderInbox) Set olMailItem = olFolder.Items.Add(“IPM.Note”) The Outlook Mail object has several properties that can be manipulated. The following is a complete code example that changes the Subject, To, Priority, and Body properties when creating a new e-mail message:Dim strBodyText As String ‘Reference the Outlook Application Dim olApp As Outlook.Application ‘The NameSpace object allows you to reference folders Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder ‘Create a reference to the email item you will use to send your email Dim olMailItem As Outlook.MailItem ‘Create the Outlook object Set olApp = CreateObject(“Outlook.Application”) Set olNS = olApp.GetNamespace(“MAPI”) Set olFolder = olNS.GetDefaultFolder(olFolderInbox) Set olMailItem = olFolder.Items.Add(“IPM.Note”) ‘Create the body of the message from the data in the form strBodyText = “Material for Order #“ & Me.OrderNumber & vbCrLf & _ “Order Due Date: “ & Me.OrderDate & vbCrLf & _ “Action: Inform customer it will be late” ‘Update the new mail object with your data With olMailItem .Subject = “Material Delay for Order #“ & Me.OrderNumber .To = “OrderEntry@AbraxisCorporation.com” .Body = strBodyText 539 Chapter 16: Working with Office Applications 47033c16.qxd:WroxProgRef 3/30/07 12:27 AM Page 539 .Display End With ‘Release all of your object variables Set olMailItem = Nothing Set olFolder = Nothing Set olNS = Nothing Set olApp = Nothing This code creates the e-mail message using only a few lines of VBA code. It builds the message text, stored in the strBodyText variable, from the OrderNumber and OrderDate data from the record cur- rently in focus on the form. Then the To line, Subject, and Body of the message are set through their corresponding properties on the olMailItem Mail object. While the message in the example contains all of the basic information a user might need to communicate, you can enhance the code just a bit to add a follow-up flag and a high priority distinction to the message. Simply add the following lines of code into the preceding With block: .Importance = olImportanceHigh .FlagStatus = olFlagMarked ‘Set the flag reminder date for two days in advance .FlagDueBy = Date + 2 Finally, calling the Display method shows the e-mail message on the screen, allowing the user to manu- ally edit and send it at his convenience. However, a common, and often desired, scenario is to just send the mail message without forcing the user to directly interact with the e-mail itself. The following code shows how the message can be sent automatically using the Send method and can replace the With code block in the preceding code. With olMailItem .Subject = “Material Delay for Order #“ & Me.OrderNumber .To = “OrderEntry@AbraxisCorporation.com” .Body = strBodyText ‘Call the send method to send the mail automatically .Send End With In Outlook 2003 and later, if the message is sent automatically and not shown to the user, the user receives a security dialog box with a message explaining that an e-mail is being sent via Outlook and giving her a chance to stop the operation from happening. This security feature was added to help stop the spread of rampant e-mail viruses, but unfortunately, it is often looked on as more of a nuisance from a developer standpoint. However, there are available methods for working around this dialog box, which are described in the next section. Working with Outlook’s Security Features If you’ve previously implemented code similar to the preceding example, you’ve encountered the secu- rity dialog box that pops up when the Send method is called, as described in the preceding section. This is actually the second of two dialog boxes Microsoft added to Outlook 2003 in an attempt to prevent potentially malicious e-mails from spreading without user knowledge or intervention. The first dialog box appears when code tries to manipulate addresses in the Contacts folder. 540 Chapter 16: Working with Office Applications 47033c16.qxd:WroxProgRef 3/30/07 12:27 AM Page 540 Sending an e-mail programmatically displays the dialog box warning that a program is trying to send an e-mail message. The user has to wait 5 seconds before choosing to send the e-mail message. However, in trusted computing environments, there may be times when it is more desirable to bypass these security dialog boxes. There are at least two possibilities for achieving this goal: configuring security through Exchange Server or using Redemption. These options are examined next. Using an Exchange Server to Configure Security First, if the users are working in an Exchange environment (or your application will be used with an Exchange Server), you have the capability to configure the Administrative Options Package for Exchange Server to allow mails to be sent automatically without security dialog boxes. The package allows users to permit programmatic sending of e-mail through configuration of a public folder and custom form stored on the Exchange Server. The advantage of this system is that you don’t need to touch the client machines at all. Once the form is installed in the public folder on the server, all you need to do is decide which types of programmatic access are needed. This package provides options to access the address book, use the Send method, and a variety of other types of settings (such as attachment blocking). The major disadvantage to this method is that unless you’re writing code within a COM add-in for Outlook, allowing programmatic sending is an all-or-nothing proposition. That is, if you allow one application to send e-mails without dis- cretion, you allow all applications using the Outlook Object Model to send e-mail without security warn- ings. Enabling these features on Exchange removes security restrictions that block potential viruses that propagate via e-mail sent from Outlook, so it is important to be extremely careful when choosing to modify the Exchange Server security settings. If you choose to use the Administrative Options package, make sure that users have virus software for both the client machines and the Exchange Server machine. Using Redemption to Work with Outlook Security Another option for preventing the Outlook security dialog boxes involves downloading a third-party DLL called Redemption. The Redemption .dll serves as a wrapper for Extended MAPI, another method of creating and sending e-mail messages. Extended MAPI isn’t affected by the Outlook security features. The advantage to Redemption is that it can be specifically targeted to a defined application, so merely having the Redemption DLL present on a system poses no security risk. The major disadvantage is that it must be registered on all machines using the applications that reference it. For single users, Redemption is free. A redistributable Redemption license costs around $100. More information about Redemption can be found on its website at dimastr.com/Redemption. Redemption is easy to use. Once the DLL has been registered on the system, create a reference to the Safe Outlook Library. Then you need to make just a few key changes to the preceding code and users will no longer be presented with the security dialog box. The following code sample takes the previous example and modifies it to use Redemption. The changes in the code are highlighted. Dim strBodyText As String Dim olApp As Outlook.Application Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder Dim olMailItem As Outlook.MailItem ‘Add a reference to the Redemption Safe Mail item Dim objSafeMail as Redemption.SafeMailItem ‘Create the Outlook object Set olApp = CreateObject(“Outlook.Application”) Set olNS = olApp.GetNamespace(“MAPI”) 541 Chapter 16: Working with Office Applications 47033c16.qxd:WroxProgRef 3/30/07 12:27 AM Page 541 Set olFolder = olNS.GetDefaultFolder(olFolderInbox) Set olMailItem = olFolder.Items.Add(“IPM.Note”) ‘Create the body of the message from the data in the form strBodyText = “Material for Order #“ & Me.OrderNumber & vbCrLf & _ “Order Due Date: “ & Me.OrderDate & vbCrLf & _ “Action: Inform customer it will be late” ‘Update the new mail object with your data With olMailItem .Subject = “Material Delay for Order #“ & Me.OrderNumber .To = “OrderEntry@FramesRUs.com” .Body = strBodyText ‘remove the “Send” method to avoid security dialogs End With Set objSafeMail = new Redemption.SafeMailItem ‘No need for the Set statement here objSafeMail.Item = olMailItem objSafeMail.Send ‘Release all of your object variables Set objSafeMail = Nothing Set olMailItem = Nothing Set olFolder = Nothing Set olNS = Nothing Set olApp = Nothing Creating Other Types of Outlook Objects from Access Creating e-mail messages in Outlook isn’t the only way to use VBA and Outlook to enhance your data- base solution. Meetings, appointments, tasks, and journal items can be managed via Outlook using VBA. For example, it is common for business users to schedule tasks in Outlook to remind them to complete an action by a certain date and time. It is very easy to create these tasks, as well as other Outlook items, with just a few lines of code. View the code behind the Create Task button’s Click event on the sample database’s Material Order Form. The initial portion of the code is very similar to the code used to create an e-mail message. However, instead of referencing the Inbox folder, set a reference to the Task folder, as shown in the following code. Dim olApp As Outlook.Application Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder Dim olTaskItem As Outlook.TaskItem Set olApp = CreateObject(“Outlook.Application”) Set olNS = olApp.GetNamespace(“MAPI”) ‘Get the Outlook “Tasks” folder Set olFolder = olNS.GetDefaultFolder(olFolderTasks) 542 Chapter 16: Working with Office Applications 47033c16.qxd:WroxProgRef 3/30/07 12:27 AM Page 542 [...]... all new in Access 2007 The following table provides a brief description of the Access 2007 features for SharePoint 2007 that you’ll explore in this chapter Feature Access Web Datasheet Enables the user to edit SharePoint lists in the Access Datasheet in the Internet browser window Also provides the Datasheet task pane for interacting with both Access and Excel Open with Access When Access 2007 is installed,... Views on SharePoint While Open in Access and Access Views 563 47033c17.qxd:WroxProgRef 3/30/07 12:27 AM Page 564 Chapter 17: Working with SharePoint from SharePoint are new to Access 2007, the Access Web Datasheet and Importing from SharePoint were both available in Access 2003, although the features were somewhat more limited in scope Access 2003 was the first release of Access to support any SharePoint... List in Access link, was originally called Create Linked Table In Access Access 2003 users will see the Create Linked Table In Access link in the task pane for both SharePoint 2003 or 2007 lists However, Track this List in Access and Create Linked Table In Access perform the same functionality: a linked table is created in a new or existing database When a SharePoint list is created in an Access database... Access When Access 2007 is installed, the Open with Access button on the Actions menu of a SharePoint list enables the user to quickly open the list in a new instance of an Access database The list can be either imported or linked Access 2007 also provides three Access application templates for select SharePoint list types Access Views on SharePoint When an Access application has been migrated and published,... have access to the SharePoint site to which the applications are linked You’ll find the samples for this chapter in the chapter’s download file Access Features on SharePoint Access 2007 has four features for SharePoint that have entry points from within the SharePoint user interface: the Access Web Datasheet, the Open with Access button on SharePoint list Actions menu, Import from SharePoint, and Access. .. chapter As with all other Office applications, adding a reference to the Microsoft Access 12.0 Object Model via the VBA References dialog box in Excel’s Visual Basic Editor is required to begin employing the Access feature set in a database solution In this example, you use Excel to start an Access database application via a button click Open the Use Access Excel workbook file included with the sample... Excel Workbook’s VBA project Pulling Data from Access There are unlimited opportunities to use VBA in an application to manipulate an instance of Access to utilize data in a database solution The Access Object Model can be managed from other applications that support VBA to enhance those applications with Access functionality This example gathers data from an Access database into an Excel spreadsheet,... user to work with Clicking the Report with Access link is equivalent to creating a link to a SharePoint table, selecting it in the Navigation pane, and then creating a new report based upon the linked table 565 47033c17.qxd:WroxProgRef 3/30/07 12:27 AM Page 566 Chapter 17: Working with SharePoint Open with Access New to Microsoft Office 2007, the Open with Access button is available on the Actions menu,... SharePoint As for Access 2007, some of the most powerful database applications can be built and integrated directly into SharePoint with extremely minimal effort from the developer The Access 2007 features for SharePoint 3.0 break out into two categories: features available on the SharePoint Server and the features used from within an Access application Some of these features were available in the Access 2003,... from an Access database and pushed the data into another Office application by automating it in an Access database solution However, it is just as easy to automate the Access Object model from another Microsoft Office application to pull data from the database The next example implements pulling data from an Access database into an Excel spreadsheet from VBA code written in the Excel Workbook’s VBA project . within Access to “push” the data into the other Office programs. ❑ Write code within those other programs to “pull” data from Access into them. Because this book is about Access 2007 VBA, most. Outlook to be manipulated directly from VBA in the Access application. In the sample database, this reference has already been set in the VBA project and if Outlook 2007 is not installed on the machine,. Outlook, using Excel features from VBA in an Access database solution requires a VBA reference to the Microsoft Excel 12.0 Object Model in the Visual Basic Editor’s References dialog box. Working

Ngày đăng: 09/08/2014, 12:22

Từ khóa liên quan

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

Tài liệu liên quan