|
|
Note: If the phrase "Tips & Tricks" is included in a topic link, there's numerous tips & tricks on that particular topic .
Can't Use the Equals Operator with Between
Caps Lock FeatureHave you ever pressed Caps Lock unintentionally? All of us have--it's easy to do because it's just above the Shift key. That's why Access disregards Caps Lock mode (when it's on) if you press the Shift key for one letter and then release Shift to type the remaining letters in your entry.
This behavior can be a real time-saver. It can also be a nuisance if you meant to enter aCCESS, not Access. If this is the case, you can turn off this feature. Choose AutoCorrect from the Tools menu, and deselect the Correct Accidental Use Of cAPS LOCK Key option. Combo Box/List BoxAutoExpandThe combo box control has a unique property named Auto Expand. The Yes setting (the default) searches the item list for the first matching item as you enter characters, and displays the first matching item in the text box. This drastically cuts down on the amount of typing you must do. If you want to accept the item, you simply stop typing.For instance, let's assume your list contains the items aardvark, annie, annotate, and anteater. When you enter the letter A, the combo's text box component displays the item aardvark--the first item in the list that matches "a". If you then enter the letter N, the text box displays the word annie--the first item in the list that matches "an". If your third letter is T, the control displays anteater. However, if you enter a second N, the text box continues to display annie. Then, if your fourth letter is an O, the control updates to display annotation. If you don't like this feature, you can turn it off. Simply set the Auto Expand property to No. back to topColumn Count You probably know that a combo box or a list box can have multiple columns. In fact, the control will display all of the fields in the bound table or query from left to right up to the number you specify as the control's Column Count property. In other words, if the bound object has ten columns and you set the control's Column Count property to eight, the control will display the first eight columns from left to right. There is one catch you might not be aware of--the Column Count property value must be an integer from 1 through 255. Neither the combo box nor the list box can display more than 255 columns. However, this limitation shouldn't cause too much trouble, since 255 columns will be more than adequate for most uses. This means the control's Bound Column property can't be greater than the Column Count property. The Bound Column property determines where the control stores its value. You can display many columns, but the control is bound to only one column. While this seems obvious, it's a mistake that's easy to make and hard to find. It's especially likely to occur if you change the Column Count property setting but forget to update the Bound Column setting.back to topCorrecting #ErrorAccess returns error messages when it can't return a value for some reason. One of the most common error messages is #Error. You'll see this when Access can't evaluate the expression. You can generally trace the failure to one main reason: You've supplied the wrong argument or you've omitted an argument.
Instead of returning the number of employees you have. Why? Take a close look at the table name--shouldn't the table's name be "tblEmployee" instead of "tblEmploye" (the incorrect reference has only one e)? A simple mistake like this can be hard to find, but not if you know where to look. Next time you encounter the #Error message, review your expression's arguments carefully for misspellings and omissions. back to topCutting Out a ReferenceIf you use DAO for referencing, you're probably familiar with the following statements:
You can eliminate a few statements by using the following form:
Making this change shouldn't cause any problems unless you reference the database object somewhere else in your code. back to topData SheetResizing Multiple ColumnsSometimes you may need to adjust the width of a data sheet's columns to view the entire contents of each cell. If it's just one column, a quick fix is to simply double-click the right border of the column's header cell (the row of gray cells along the top). Doing so increases the size of that column so it can accommodate the longest entry in that column. You can also resize several columns at the same time by selecting multiple columns and then double-clicking the right border of any column header cell within the selection.There are two ways to select multiple columns.
Using this method, you can also reduce the column width(s). back to topSelecting the Whole CellIt's easy to select a cell in data sheet view--simply click it. However, doing so doesn't select the entire entry or even the entire cell. It selects a portion of the entry, depending on where you click. Access selects the entry up to the cursor. Pressing F8 extends the selection to the end of the current word. In other words, pressing F8 continues to extend the selection--by components--until you've selected the entire cell. For instance, if you click between the P and the I in the entry Apple Pie, Access selects "ie". Pressing F8 extends that selection to include the entire word, "Pie". A second press selects "Apple Pie" and a third press selects the entire cell. back to topFieldsAdding Fields to an Existing FormIt's better to include only the needed fields and then go back and add fields later if necessary. To add a field to an existing form:
back to topAvoid Using Duplicated Field NamesAccess forces you to use unique filed names in each table. You can, however, use the same names in other tables. For instance, all your tables can have a field name LastName. It is recommended to avoid repeating filed names across tables whenever possible. You'll find your tales much easier to work with if each filed name is unique. back to topChanging Data TypesAnytime you need to store decimal values, you must remember to declare the field or variable's data type as Single or Double. If you forget, you can always change the data type later to accommodate decimal values. However, we would like to offer one word of caution about doing so. If you change a data type after you've entered data, you risk losing that data, and you can't undo the damage. Here's what happens: If an existing value is too large for the new data type, Access may truncate, round, or even delete that value. This caution applies anytime you change a field property when data already exists.back to topUsing the Field ListYou may want to add several fields, and dragging them one at a time can get tedious. You can rely on a few selection tricks to drag more than one field to your form at a time.
back to topFile ManagementCompacting DatabaseCompacting your databases regularly will improve your application's speed, which defragments your database. When saving a file, seldom does the file save in one continuous block. The disk manager starts at the center of the disk and fills in empty blocks of memory with each saved task. If the first free block isn't large enough to hold the entire file, the disk manager saves only the portion that fits. Then the disk manager moves on to the next hole and fills it up. The disk manager continues in this manner until it has saved the file. If the files is particularly large, it could be spread all over your disk in several noncontiguous blocks. As a results, it takes longer to load the file and access information as you work with it. Another benefit of compacting is the reduction in the size of your file. Compacting, in most cases, significantly reduces the size of your file - especially if you add and delete records on a frequent basis. It is recommended that you make compacting a regular part of your database routine. back to topFilters Slow Down FormsIf you use the Filter By Form feature, you may notice that your form takes a little longer to close. That's because Access saves the last filter when you exit your form, which slows things down a bit. If your form has a Close or Exit button, you can easily solve this problem. Simply add the following line of code to your close or exit procedure: DoCmd.Close acForm, "frm_MyForm", acSaveNo. The acSaveNo argument tells Access not to save the form before it shuts down, so your form closes quickly.back to topFormsAdding Fields to an Existing FormIt's better to include only the needed fields and then go back and add fields later if necessary. To add a field to an existing form:
back to topContinuous Forms & SubformsContinuous forms are great for viewing several records at the same time. However, you can't view a form in Continuous mode if that form contains a subform, an ActiveX control, or a bound chart. If your form contains one of these three objects, you must set the main form's Default View property to Single Form or Datasheet. If you really must view the main form in Continuous mode, try working with two forms--one with the embedded object and one without--and use a pop-up form to display the embedded subform or chart.back to topOpening to a Specific RecordBy default, a form displays the first record in the underlying record set. Perhaps the easiest method is to use the GoToRecord method in the form's Open event. The GoToRecord method uses the syntax DoCmd.GoToRecord acForm, "formname", acGoTo, recordnumber where acGoTo is an intrinsic constant and recordnumber is the numeric value that equals the record you want to view--in other words, the record number.back to topRestricting Data EntryAccess forms, by default, allow users to add new records. An easy trick that inhibits this behavior. You simply add a required field to your form and then don't display that field on your form. That way, the underlying table won't accept a new record because the user can never supply data for the required field. There's an easier way, though, and it's built right into the form.
back to topSpeeding Up Your FormYou're probably always looking for ways to speed up your form performance. One easy way is to include only those fields you need from the record source. Generally, it's easier just to include all the fields, whether you're using a wizard or working from scratch to create your form. However, every field slows things down a bit. So the next time you get ready to include all those extraneous fields, stop. Think about your form's purpose and add only the necessary fields. You can always go back and add a field later if it becomes necessary. back to topGenerating a Days-Outstanding ValueThis tip was sent in by Jonathan Mueller working in TRU's MIS Client Services Department, Paramus. For you VBA, Access or Excel gurus this tip is for dealing with dates that may or may not be valid anymore: In databases that track billing and payment transactions, you'll often want to display the number of days an invoice or other item is outstanding.
This expression subtracts the current date from the invoice's creation date and returns the result as the number of elapsed days. By itself, however, this expression continues to generate the days-outstanding value even when the invoice is paid or completed. To prevent this, use the modification:
This expression first subtracts the date in [DatePaidInFull] from [DateCreated]. If [DatePaidInFull] is null, however, then this expression also returns a null value. As a result, Access evaluates the second expression in the Nz() function and subtracts the current date from the invoice's creation date as we explained earlier. back to topGetting Rid of a Blank RecordMost people consider the blank record at the bottom of a continuous form a nuisance. You can use the Allow Additions property to inhibit the blank record in a continuous form. Of course, this means you can't add more records, but that's not generally a problem. Few people use continuous forms for data-entry purposes. Rather, they use continuous mode to view several records at the same time.back to topImporting/ExportingExporting SelectionsYou can easily export Access objects to foreign formats using the Save As/Export command.
You can also save selections of data instead of the entire object using the same routine. However, instead of selecting the object in the Database window:
back to topImporting DataYou can import foreign data into an Access table. You can't import just any data, though--Access must recognize the data's format. Generally, you can easily import data from Excel, FoxPro, dBase, and Approach. You can also import data stored as text. The key to successful importing is making sure the structure of the foreign data and of the table into which you're importing match. If the foreign file doesn't resemble your table, you may experience some errors. Often these are unavoidable. However, editing your foreign data before importing it can save a lot of errors. Sometimes the Import wizard doesn't always work. Lots of times, Access just doesn't interpret the format of the data and returns errors. When this happens, try to find a go-between format. For instance, if you're having trouble importing data from Lotus Approach, try saving the Approach file in another format, such as dBASE, and then try importing that file instead of the Approach file. Often you'll find Access interprets the data just fine once it's in a more compatible formatback to topIndexesIndexes can be confusing to even the experienced Access user. The first thing you should know about an Access index is that an index is really an internal function. Access uses an index to sort data in a logical order; that order is determined by the field's data type. You can define an index, but beyond that, you have little control. You might think the more indexes, the faster your application--but you'd be mistaken. Indexes, if applied incorrectly, can slow down your application. That's because Access updates an index each time you add or modify a record if you index more than one field. A few guidelines can help you define efficient indexes. First, primary key fields are automatically indexed. Beyond that, most tables will not require further indexing. If you feel the need, your index candidate should meet all of the following conditions:
back to topLinking to another DatabaseCreating a link to another database programmatically can involve a lot of referencing and coding, if you use the traditional method. That method involves creating a tabledef object and then using that object's properties to connect and refresh the link. We've got some code that uncomplicated the task. Next time you need to link, try this procedure:
The For loop cycles through each table in the database specified in the variable strPath. During each loop, the TransferDatabase sets a link to each table. The above For loop does have one drawback--it also links the system tables. To avoid this, use the following loop:
back to topMeasurementsAccess allows you to use almost any unit of measure you like when working with objects. For example, you can specify an object's size in inches or centimeters. Access itself, on the other hand, uses a measurement known as twips. You can use the following information to help convert a unit of measure to twips:
back to topNull ValuesDon't let Null values intimidate you--they can be confusing even for the experts. Fortunately, a few basic principals should help you out.
When a value is missing or unknown, it simply means the information may exist--we simply don't know it. Occasionally, the information doesn't apply to a particular record and you must leave a field blank. Let's suppose you've got a table of phone numbers and two fields are blank.
Using Null Values vs. ZeroesYou need to be careful about using null values in place of zeroes in Access.
back to topPrimary Key FieldYou cannot leave a field blank if that field is a primary key field. A primary key value uniquely identifies each record. It stands to reason that you wouldn't want to leave a primary key field blank, so Access simply doesn't allow you to. While designing your tables, be sure the field you choose as your primary key field can stand up to this Null test. On the other hand, foreign key fields can contain blanks, but you'll rarely need to leave a foreign key field blank. back to topNumber of Characters in an ExpressionDid you know that there's also a limit on the number of characters you can use in any expression? An expression can contain up to 2045 characters. While this should be adequate most of the time, it is possible to write an expression Access simply can't evaluate because it's too long. If this should happen to you, there's no easy workaround. Perhaps the best solution is to write your own procedure function and break down the expression into components rather than trying to write the entire task as one statement.back to topObjectsObject PropertiesMost objects have two properties that are easy to confuse--the Name and Caption properties.
Let's compare the two properties on a simple command button. You might name the button cmdButton. When you refer to the button in events or other code, you'd use the Name property string--cmdButton. On the other hand, if this same cmdButton's task is to print a specific report, cmdButton's Caption property might be Print Report. As you can see, the two property settings aren't interchangeable, but we can understand how people might get them confused. back to topUpdating CodeChanging the name of an object in Access is a not easy; Access doesn't update all your references; you must do that yourself. Invariably you miss a few, and they'll eventually cause trouble. Fortunately, updating these references in your modules is fairly easy. Simply use the Replace feature.
Access highlights each occurrence of the original name and asks if you want to replace it. Updating object names this way is quick and thorough. back to topPercentage/Top ValuesYou can return a percentage of records using the Top Valuesproperty.
back to topPrinting OptionsPrint Preview the Easy WayDid you know that you can use Print Preview from the Database window and do not have to open the object first. Instead of opening the object and then previewing it:
You can view most of your objects in Print Preview, simply by selecting the object you want to view in the Database window and clicking the Print Preview button, located on the toolbar. If the button isn't available, choose Print Preview from the File menu. Previewing an object in this manner give you a quick look at your object, its structure, and in some cases, its data. The benefit is saved time and paper. Another advantage of Print Preview is the capability to print just one page of a report instead of the entire report.
This is a great way to save time and paper when only a portion of a report is needed. You don't have to create a new report, nor do you have to print the entire report--simply print the needed pages from an existing report. back to topQueriesA Better QueryYou might think one is more efficient than two, but that's not always the case. For instance, if you're running a Totals query that includes a JOIN, you might consider breaking that query into two parts:
In this particular case, the two queries are usually faster than the comparable lone query. back to topCombining SQL Statements to create Union QueriesA union query combines similar tables. The resulting set is never wider than either table, but generally contains more records than either of the underlying queries or tables, since the purpose is to combine the two tables. For instance, let's suppose you have historical data for the last five years in one table, and you base two queries on that table. One query returns all the records for 1998; another returns all the records for 1994. To combine the two queries, you'd create a UNION query. Y
Of course, if you know the exact SQL statement, the hard way is really the easier way. However, few of us get a SQL statement right on the first try, so if you're not an expert, our easy way might be the easiest way for you. Just remember--this only works with UNION queries. back to topFinding the Highest & LowestYou can sort the results of a query to position a high or low value at the top of your record set. Simply set the Sort order in the query design grid for the field you want to sort by. If you'd like to return just one record--either the highest value or the lowest value in a particular field--you'll need the Top Values property.Let's suppose you want to see the largest order for a specific time period. In your query design grid, you might include the order number, the company, the salesperson who made the sale, the date he or she made the sale, and the total amount of the sale. To specify a specific time period, you'd enter a criteria expression in the Date field's Criteria sale. Then you'd assign the Descending sort property to the Amount Of Sale field. Now you're ready to set the Top Values property. First, right-click the query design grid (click the background, don't click a field). In the resulting shortcut list, choose Properties to open the query's property sheet. Find the Top Values property and enter the value 1. Then run the query to return the number one sale for the specified time period. You can also return the lowest sale. Simply change the sort order to Ascending and run the query again. Just because you set the Top Values property to 1 doesn't mean you'll return just one record. If all the criteria are met and the sort field has more than one record with the same value, the query returns those records. For instance, our previous example could return more than one record for the number one order if another order of the same amount exists within the same time period. Of course, in this example, the chances are slim that this will happen. Running a Query from a MacroYou probably know that you can use the OpenQuery macro action to run an existing query. What you might not realize is just how easily you can create that macro.
back to topSaving a SQL Statement as a Query
back to topTotal Query for Multiple CriteriaNeed a total based on criteria? A Totals query works fine until the criteria involve a range of values instead of just one. For instance, let's suppose you want to sum percentage values by regional status. If you just want to sum percentages for all the records that pertain to one region, a Totals query will work just fine.If you want to sum all the percentages for more than one region, you may run into difficulty. A Totals query will return the result you need--you just need to rethink the criteria. For instance, in this situation, you'd simply group the Totals query by the Region field and Sum the Percentage field. To narrow the criteria, you'd still select Sum from the Percentage field's Total field. But here's the trick: Specify the criteria in the Percentage field's Criteria cell. For instance, to sum all the percentages for Kentucky, Indiana, and Ohio, you'd use an expression similar to this: [Region] = "KY" Or "IN" Or "OH" The results of the query will be one value--the sum of the percentage values in Kentucky, Indiana, and Ohio. Using the Hourglass MethodMost tasks run lickety-split in VBA, but occasionally we run across a procedure that takes a little more time than expected. This can happen when you're working with a complex query or an especially large record set. When this happens, your user won't really know what's going on and might try to continue working. Anytime you find your code ties up processing, use the Hourglass method to display the hourglass mouse pointer. That way, your user knows something is happening behind the scenes and waits (you hope).To display the hourglass pointer:
back to topRecord Count
back to topIf FindNext Doesn't WorkYou can use the Recordset object's FindNext method to locate records that match given criteria. Simply use the form: rst.FindNext criteria where criteria is a SQL WHERE clause without the WHERE. For instance, you might use the statement rst.FindNext "[LastName] = 'Smith'" to find the next record with the string Smith in the LastName field. However, occasionally these statements don't work, and you can waste a lot of time trying to figure out what's wrong with the criteria component. Most likely there's nothing wrong with your criteria component. Rather, you've not defined the correct Recordset type. You need to define the Recordset as a Dynaset using the form: db.OpenRecordset("tablename", dbOpenDynaset) If you omit the type argument for your statement, Access opens a table-type Recordset (dbOpenTable) unless you specify a linked table or a query. In those cases, the default is the Dynaset-type. So before you waste a lot of time trying to restate your criteria expression, check the Recordset's type. back to topQuick Record CountThe Recordset object has a few properties, and one of those properties is RecordCount. As its name implies, this property returns the number of records accessed by the Recordset object. (The TableDef object also supports the RecordCount property.)To get an accurate count, you can use the MoveLast method to access the last record and then assign the RecordCount property to a variable using a code snippet similar to the following:
back to topUsing CountDid you know that Count() is really a SQL function and not one of Access's native functions?
However, if you're not using a traditional SQL statement in which you can also specify criteria, you should consider using the syntax Count(*) The second form is much faster than specifying a particular field name. back to topRelationshipsAutomatic RelationshipsRelationships are the real power behind Access. Relating tables allows you to omit redundant data, which saves resources and your time.
If you don't want Access to create relationships automatically, you can turn this feature off.
back to topRelationship WindowYou can create a relationship with the Relationships window.
back to topReportsReporting the Easy WayThere are several ways to create an Access report--you can use a report wizard or you can build it from scratch. If you have a form based on the same table or query, you might be able to use a different approach.
Of course, this shortcut won't always be appropriate, but when it is, it can be a real time-saver. back to topRounding Decimal ValuesIf you're rounding decimal values to an integer, you don't really need special expressions for rounding. Simply assign the value of your procedure as an Integer data type.Function BMI(pounds As Integer, feet As Integer, inches As Integer) As Integer By assigning the entire procedure to an Integer value, we limit our function to returning only Integer values; therefore, it rounds automatically. If the result of the expression is 21.45, the function returns 21; if the result is 22.55, the function returns 23. The function doesn't care how many decimal values the expression returns. While this isn't a typical programming approach, it is a quick solution in the right situation. back to topSort Order is SavedDid you know that Access saves the last sort order in a form, query, or table? That means the next time you open that object, Access will remember the sort order you chose last and sort the object accordingly. For instance, the default sort order is ascending.
This behavior is also true of tables and queries. back to topSpreadsheets are for ExcelIf you're new to Access, you may be making a mistake that's fairly common to new users. That mistake is wanting your tables to resemble spreadsheets. Keep in mind that a table isn't a spreadsheet at all, just a means of storing data. If you dump all of your data into one table, you're missing the point--and power--of using a relational database. If you suspect you might be storing data incorrectly, check for redundant data. Do you often repeat the same information, such as a customer's address? If so, you're probably using Access tables as you would an Excel spreadsheet. How do you fix the problem? Apply the following rules of normalization when creating tables:
Learning how to moralize data can seem a bit intimidating, but it's easy once you get the hang of it. The best way is to read about it and then practice. back to topSQLCreating SQL StatementsSQL statements are one of the more difficult components of VBA code to work with. There are a lot of rules, particularly when it comes to delimiting strings and concatenating variables. A good starting point is to let Access build as much of the statement as you can. How? There are two ways.
As a rule, neither method will give you the exact statement you need, but it's a good place to start. back to topDeBugging SQL StatementsHere's a good rule to follow when debugging it.
back to topControlling SQL StringsWhen copying a SQL string from the SQL window to a module window, it's usually in block form instead of being one long statement. As a consequence, you then have to assemble all the clauses on one line, and doing so often produces an "Expected Case" error, which you must clear before you can continue. You can easily avoid this error by reconstructing your statement from the bottom up.
back to topFaster QueriesIt's common to use a SQL statement as a combo or list box's Record Source. You'll often see SQL statements used as a form's Record Source property. However, a SQL statement can slow things down a bit. That's because the Jet optimizer preoptimizes a saved query. In contrast, this doesn't happen with the SQL statements, which means they require optimizing over and over again at runtime. If your application contains many of these statements, you may want to reconsider your design. However, most applications won't show much improvement, so only consider this change if your forms or controls are slow enough so your users notice the wait.back to topSaving a SQL Statement as a Query
back to topUsing CountDid you know that Count() is really a SQL function and not one of Access's native functions?
However, if you're not using a traditional SQL statement in which you can also specify criteria, you should consider using the syntax Count(*) The second form is much faster than specifying a particular field name. back to topToolbarsDefault Status Bar MessageWhen creating a new table, have you noticed the Description field to the right of the Data Types field? You can enter descriptive or explanatory text in this field. You might find this extra step unnecessary. However, if you knew you could use it to display a message in the Status Bar automatically, would you pay more attention to it? Well, that's how it works. In Form View, Access displays the contents of a field's Description field when that control has focus. Not only can you use this as a means of explaining your field, you can also communicate information to your users.back to topDocking ToolbarsIn Access 97, toolbars are very easy to modify and to position. There are two positions, docked and floating toolbars.
You can alternate between a docked and floating toolbar by simply double-clicking the toolbar.
back to topResetting ToolbarsTo reset the toolbar to its default settings:
back to topUpdating CodeChanging the name of an object in Access is a not easy; Access doesn't update all your references; you must do that yourself. Invariably you miss a few, and they'll eventually cause trouble. Fortunately, updating these references in your modules is fairly easy. Simply use the Replace feature.
Access highlights each occurrence of the original name and asks if you want to replace it. Updating object names this way is quick and thorough. back to topUppercase LettersThere are a couple of ways to display text in uppercase letters.
back to topVariable Doesn't Work?When a value doesn't display or consider a decimal component in a calculation--and you know it should--check that value's data type. The value must be a Single or Double data type to store a decimal component. This is a common mistake, and it's easy to make. While it's obvious that the Integer and Long Integer data types both store integers, we use them so often that's it's easy to enter Integer or Long without realizing the repercussions. Another problem is that we don't always know during the design stage that a variable might need to accommodate a decimal value.back to topVBAProperty or Method?If you're fairly new to VBA, you may be a little confused about properties and methods, since the syntax for both is similar. By that, we mean that you separate both a property and a method from the object with the dot identifier (.). For instance, to set a property, you'd use the form: object.property
Methods, on the other hand, generally execute some behavior or action. For instance, the Requery method updates the data underlying a specific form (or object). Requerying a form might require a statement similar to: frm.Requery Running an Event with the Event
back to top |