![]() | ![]() | |
The integrated Office solution you're about to create involves a fictitious set of data representing an energy usage log for a computer lab in your company. The solution is called "Energy Management," and it tracks a lab's energy use over a one-month period so that management can do a cost assessment and determine ways of reducing energy costs.
The Access database that stores the energy usage data consists of three main elements. The first element is the table containing the data. The second is the user interface, or dialog box, where you select the document items you want to automatically generate. The third is the code, contained in the various code modules, that creates the selected document items. The steps in this chapter show you how to create all three elements of the database.
In this fictitious solution, a digital meter connected to a computer automatically generated the text file. The hardware and software associated with the meter automatically fed the data to the text file.
Because you're importing a comma-delimited text file containing data that was automatically generated by the tools connected to the circuits, you should accept the default settings in each step of the wizard.
Close Window
The table is now ready for exporting data to Word, Excel, and PowerPoint, and you can start creating the dialog box that will display your document options.
Check Box control
Command Button control
Label control
NOTE
Unlike the CheckBox control in the UserForm of the Visual Basic Editor, which has a Caption property, the label associated with a Check Box control in an Access form is listed as a separate control in the Properties window. Select the label of the check box to set its properties.
Control | Property | Value |
---|---|---|
Check0 | Name | chkWord |
Label1 | Name | lblWord |
Label1 | Caption | Microsoft Word report |
Check2 | Name | chkExcel |
Label3 | Name | lblExcel |
Label3 | Caption | Microsoft Excel workbook |
Check4 | Name | chkPowerPoint |
Label5 | Name | lblPowerPoint |
Label5 | Caption | Microsoft PowerPoint presentation |
Check6 | Name | chkOutlook |
Label7 | Name | lblOutlook |
Label7 | Caption | Microsoft Outlook e-mail message |
Command8 | Name | cmdOK |
Command8 | Caption | OK |
Command9 | Name | cmdCancel |
Command9 | Caption | Cancel |
Command9 | Cancel | Yes |
Label10 | Name | lblGenerate |
Image11 | Name | imgLogo |
Image11 | Size Mode | Stretch |
Control | Property | Value |
---|---|---|
Label12 | Name | lblProgress |
Label13 | Name | lblCurrentRecord |
Label14 | Name | lblOf |
Label15 | Name | lblTotalRecords |
In the Form Design window, click anywhere outside the form design area to display the list of properties for the form. (You may have to scroll down in order to display the area below the form design area.)
Property | Value |
---|---|
Caption | Energy Management |
Record Selectors | No |
Navigation Buttons | No |
Dividing Lines | No |
Border Style | Dialog |
Shortcut Menu | No |
Try selecting and clearing the check boxes. Notice that the Form Design window creates forms just like UserForms in the Visual Basic Editor of Word, Excel, and PowerPoint does.
Close Window
Before adding code, you may want to click the Design button and move or resize the controls to resemble the preceding illustration. press F5 to display the form, click the Close Window button to close it, and then save your changes.
Dim bReport As Boolean, bSheet As Boolean Dim bPres As Boolean, bEmail As Boolean If Me.chkWord.Value = True Then bReport = True If Me.chkExcel.Value = True Then bSheet = True If Me.chkPowerPoint.Value = True Then bPres = True If Me.chkOutlook.Value = True Then bEmail = True modMain.Main bReport, bSheet, bPres, bEmail DoCmd.Close acForm, "frmMain", acSaveNo |
The first two lines contain declarations of the Boolean variables bReport, bSheet, bPres, and bEmail. By default, the Boolean variables are set to False when they're declared. The four If…Then condition statements that follow check the value of each check box in the form frmMain and set the appropriate Boolean variable. The Me keyword represents the form in which the code you're writing resides. Once you set all the Boolean variables, the program calls the Main procedure in the code module modMain, which you'll create next. The Boolean variables are passed as arguments to the Main procedure.
By default, the click event procedure is displayed in the code window.
DoCmd.Close acForm, "frmMain", acSaveNo |
You can specify three arguments in the Close method of the DoCmd object in Access. The first argument is the object type you want to close, the second is the name of the object you want to close, and the third sets whether to save changes to the object when it's closed. In the line of code you just added, you close the Access form frmMain without saving changes to the form in the database.
Close Window
Save
You've now completed the dialog box your users will interact with to generate their required Office documents from the data in the database. You now have to add code to create each of the Office documents listed in your custom dialog box.
You're going to write code that accesses all of these object libraries so that you can create each type of document.
Public g_sgTotalCost As Single Public g_iTotalHours As Integer Public g_sDBProjectPath As String Public Const g_sCircuit As String = "Computer Network" Const m_sgCost As Single = 1.075 Const m_iWattage As Integer = 560 |
The first two declarations are public variables used to total the data in the database. The public constant g_sCircuit is set to "Computer Network," the circuit that the procedure will analyze. Later you can reset it to "Lighting" so you can analyze the lighting data. You declare the public variable, g_sDBProjectPath, as a string; you'll use it to assign the file path of the MyEnergy database.
In this solution you'll use a supporting file, a Word template, to help create a report in Word. To keep the code of this solution from being complex, the Word template file should be copied to the same folder as the MyEnergy database, because the path to the database file can then easily be retrieved in code. In addition, the path to the database also specifies where to save the Word, Excel, and PowerPoint files created by this example. The two module-level constants, m_sgCost and m_iWattage, are values used to calculate the energy cost.
NOTE
After you complete the steps in this chapter and you want to move or copy the MyEnergy.mdb file created in this chapter to another disk folder, you also need to copy the file EnerRpt.dot from the Chapter 8 practice folder to the new disk location. If you do not, and you run the form in the MyEnergy.mdb database to create a Word report, an error will occur, because the EnerRpt.dot template file used to create the Word document will not be found.
Sub Main(bReport As Boolean, bSheet As Boolean, _ bPres As Boolean, bEmail As Boolean) g_sDBProjectPath = Application.CurrentProject.Path & "\" End Sub |
The Click event procedure for the cmdOK command button that you added to the form frmMain will call the Main procedure. The four Boolean variables passed into the Main procedure indicate which check boxes were selected in the form frmMain. You set the Boolean values in the Click event procedure of cmdOK.
This procedure assigns the g_sDBProjectPath variable to the Path property. In this example, the Path property returns a string value that is the pathname to the disk location of the Access database MyEnergy.mdb.
If bReport = True Then modWord.CreateWordDocument End If If bSheet = True Or bPres = True Then modExcel.CreateExcelSheet End If |
If the Boolean variable bReport is passed into the Main procedure with a value of True, the program calls the procedure CreateWordDocument, located in the code module modWord. If the Boolean variable bSheet or the Boolean variable bPres is passed into the Main procedure with a value of True, the program calls the procedure CreateExcelSheet, located in the code module modExcel. In order to create a presentation with the data in a chart, you first have to create the chart in Excel. You'll create the procedures CreateWordDocument and CreateExcelDocument later in this chapter. These two procedures create a document and a worksheet ready for the database information.
GetDatabaseInfo bReport, bSheet, bPres, True |
The GetDatabaseInfo procedure retrieves the information from the database and sends it to Word and Excel. The Boolean variables bReport, bSheet, and bPres are passed to the procedure so that you can check whether you need to pass the data to Word or Excel.
The last argument in the GetDatabaseInfo procedure indicates whether the Access form, frmMain, should be updated. Because the line of code above calls the GetDatabaseInfo procedure from within the Main procedure, and the Main procedure is only called when clicking OK on the form frmMain, this value is always set to True. As you'll see later in this chapter, when you test your code for creating the Word, Excel, and PowerPoint documents, this argument is set to False because running the procedure you'll use to test your code does not require the form to be displayed.
If bReport = True Then modWord.AddTotalRow End If If bSheet = True Or bPres = True Then modExcel.CreateChart End If If bPres = True Then modPowerPoint.CreatePowerPointPres End If If bEmail = True Then modOutlook.SendEmail bReport, bSheet, bPres End If |
If the Boolean variable bReport is True, the procedure adds the row containing the total cost and energy usage to the report. If the Boolean variable bSheet or bPres is True, it creates an Excel chart. If the Boolean variable bPres is True, the procedure also creates a PowerPoint presentation that uses the Excel chart created in the procedure CreateChart. If the Boolean variable bEmail is True, it creates an Outlook e-mail message.
You've now completed the Main procedure, which is the heart of the program. Now you need to create the supporting procedures that you called.
Sub GetDatabaseInfo(bReport As Boolean, bSheet As Boolean, _ bPres As Boolean, bUpdateForm As Boolean) Dim sID As String, sDateTime As String Dim sComputer As String Dim sgPeriodkWh As Single, sgCost As Single Dim iCounter As Integer Dim rstEnergy As New ADODB.Recordset rstEnergy.Open "LabEnergyUsage", CurrentProject.Connection, _ adOpenStatic End Sub |
The first two lines of the GetDatabaseInfo procedure declare variables that are set to the data in the database. The variable rstEnergy is declared as the type Recordset defined in the ActiveX Data Objects (ADO) object library. You use the Recordset object to assign data in a database table. Following the Recordset declaration, the variable rstEnergy is set to the recordset found in the table LabEnergyUsage in the MyEnergy.mdb database.
With rstEnergy If bUpdateForm Then Forms("frmMain").Controls("lblTotalRecords") _ .Caption = .RecordCount End If Do sID = .Fields("Id") sDateTime = .Fields("Date and Time") sComputer = .Fields("Computer Network") If bUpdateForm Then Forms("frmMain").Controls("lblCurrentRecord") _ .Caption = .Fields("Id") DoEvents End If .MoveNext Loop Until .EOF = True .Close End With |
The For…Next loop iterates through the recordset, setting the value in each field (Id, Date and Time, and Computer Network) to the declared variables. The last line in the Do…Loop moves to the next record in the recordset, making that record the current record. When the recordset is first opened, the first record in the recordset is, by default, the current record. When the last record is the current one, the EOF property is set to True and the Do…Loop exits. After the Do…Loop exits, the recordset closes.
The two lines within the With…End block that manipulate the Label controls on the form frmMain are used to update the captions of the Label controls. This way you have a visual representation of the loop's progress. The keyword DoEvents is a built-in Visual Basic function used to make sure that the screen is updated to reflect the changes in the form and in the Label controls.
sgPeriodkWh = m_iWattage * Int(sComputer) / 1000 sgCost = sgPeriodkWh * m_sgCost g_sgTotalCost = g_sgTotalCost + sgCost g_iTotalHours = g_iTotalHours + Int(sComputer) |
If bReport = True Then modWord.AddToTable sID, _ sDateTime, sComputer, sgPeriodkWh, sgCost End If If bSheet = True Or bPres = True Then modExcel.AddToSheet sID, _ sDateTime, sComputer, sgPeriodkWh, sgCost End If |
Once the data is set to the variables sID, sDataTime, and sComputer and the appropriate calculations are made, the two condition blocks above determine whether the data is written to the Word report, the Excel workbook, or both. The second If…Then condition block also checks the value of bPres, because to create a presentation in PowerPoint you first have to send the data to Excel so that you can create a chart. After that, you copy the chart into the presentation.
The code module modMain contains the procedure Main, which is called by the Click event procedure of the cmdOK command button on the form frmMain. The module modMain contains all the code that pertains to opening and retrieving information from the database, as well as the code that determines which Office document to create. In the following sections, you'll create code modules that allow you to create each Office document.