1. Trang chủ
  2. » Công Nghệ Thông Tin

Access 2007 VBA Programmer’s Reference phần 10 pps

120 456 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 120
Dung lượng 2,83 MB

Nội dung

Declaration Declare Function RegLoadKey Lib “advapi32.dll” _ Alias “RegLoadKeyA” _ByVal hKey As Long, _ByVal lpSubKey As String, _ByVal lpFile As String As Long 993 Appendix I: Windows

Trang 1

Return value Long Integer: Zero (ERROR_SUCCESS) on success The function will

return ERROR_MORE_DATAif the data passed to pvDatais not largeenough to hold the data retrieved in the value

All other values are the specific error code

RegLoadAppKeyDescription Loads a Registry hive from a file that was saved from the Registry or

with RegSaveKey

Declaration Declare Function RegLoadAppKey Lib “advapi32.dll” Alias

“RegLoadAppKeyW” _(ByVal lpFile As String, _ByRef phkResult As Long, _ByVal samDesired As Long, _ByVal dwOptions As Long, _ByVal Reserved As Long) As LongParameters lpFile — String: Name of the file that contains the Registry information

phkResult — Long Integer: Variable to receive the handle to theRegistry key that is opened with RegLoadAppKey

samDesired — Long Integer: One or more KEY_constants that bine to define the operations that are allowed for this key You can findthese constants at the end of this appendix

com-dwOptions — Long Integer: If set to REG_PROCESS_APPKEY, indicatesthat this hive can only be loaded by the calling process Cannot beloaded by other processes if it is currently loaded

Reserved — Long Integer: Reserved for future use Set to zero

Return value Long Integer: Zero (ERROR_SUCCESS) on success All other values are

the specific error code

RegLoadKeyDescription Creates a new subkey (whose information is loaded from a file that was

created using the RegSaveKeyfunction) under the specified key

Declaration Declare Function RegLoadKey Lib “advapi32.dll” _

Alias “RegLoadKeyA” ( _ByVal hKey As Long, _ByVal lpSubKey As String, _ByVal lpFile As String) As Long

993

Appendix I: Windows Registry Information

Table continues on the next page

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 993

Trang 2

Parameters hKey—Long Integer: HKEY_LOCAL_MACHINE, HKEY_USERS, or the

handle of a key returned by the RegConnectRegistryfunction.lpSubKey—String: Name of the new subkey to create

lpFile—String: Path and name of the file to load

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegLoadMUIString

Description Reads the specified string from the specified key and subkey

Declaration Public Declare Function RegLoadMUIString Lib

“advapi32.dll” Alias “RegLoadMUIStringW” _(ByVal hKey As Long, _

ByVal pszValue As String, _ByVal pszOutBuf As String, _ByVal cbOutBuf As Long, _ByRef pcbData As Long, _ByVal Flags As Long, _ByVal pszDirectory As String) As LongParameters hKey—Long Integer:Handle to an open Registry key

pszValue—String: Name of the value for the key or subkey toretrieve

pszOutBuf—String: Buffer that will receive the string from the function.cbOutBuf—Long Integer: Length of pszOutBuff

pcbData—Long Integer: Receives the length of the data that isreturned into pszOutBuff

Flags—Long Integer: When set to REG_MUI_STRING_TRUNCATE,indicates that the string that is returned is truncated to fit in pszOutBuf.pcbDatamust be set to NULLwhen this flag is set

pszDirectory—String: Path to a directory (optional)

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

Appendix I: Windows Registry Information

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 994

Trang 3

RegNotifyChangeKeyValueDescription Provides the mechanism to be notified when a Registry key or any of its

subkeys is changed

Declaration Declare Function RegNotifyChangeKeyValue _

Lib “advapi32.dll” ( _ByVal hKey As Long, _ByVal bWatchSubtree As Long, _ByVal dwNotifyFilter As Long, _ByVal hEvent As Long, _

ByVal fAsynchronus As Long) As LongParameters hKey—Long Integer: The handle of the key to watch, or one of the

hive constants listed earlier

lpWatchSubTree—Long Integer: Boolean flag that indicateswhether to watch the subkeys for change Zero: Do not watch subkeys.True (nonzero): Watch subkeys

dwNotifyFilter—Long Integer: One of the following constants:REG_NOTIFY_CHANGE_ATTRIBUTES(to detect changes to a key’s attrib-utes); REG_NOTIFY_CHANGE_LAST_SET(to detect changes to a key’s lastmodification time); REG_NOTIFY_CHANGE_NAME(to detect changes to akey’s name, or the creation or deletion of keys);

REG_NOTIFY_CHANGE_SECURITY(to detect changes to a key’s securityinformation)

hEvent—Long Integer: A handle to an event This parameter isignored if fAsynchronus= False (zero)

fAsynchronous—Long Integer: Boolean flag that indicates whetherthe function returns immediately when a change is detected True(nonzero): The function returns immediately, but the event specified byhEventis signaled when a change is detected False (zero): The functiondoes not return until a change is detected

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

Comment To use this function, you must understand how to detect and act upon

system events, a topic which is beyond the scope of this book

RegOpenKeyExDescription Opens an existing key This is a more sophisticated function than

RegOpenKey, and is recommended for use on Win32

995

Appendix I: Windows Registry Information

Table continues on the next page

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 995

Trang 4

Declaration Declare Function RegOpenKeyEx Lib “advapi32.dll” _

Alias “RegOpenKeyExA” ( _ByVal hKey As Long, _ByVal lpSubKey As String, _ByVal ulOptions As Long, _ByVal samDesired As Long, _phkResult As Long) As LongParameters hKey—Long Integer: Handle of the key to open, or one of the hive

constants listed earlier

lpSubKey—String: Name of the key to open

ulOptions—Long Integer: A reserved parameter Set it to zero.samDesired—Long Integer: One or more KEY_constants that com-bine to define the operations that are allowed for this key You can findthese constants at the end of this appendix

phkResult—Long Integer: A variable that is loaded with a handle tothe opened key

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegQueryInfoKey

Description Retrieves information about an existing key

Declaration Declare Function RegQueryInfoKey _

Lib “advapi32.dll” _Alias “RegQueryInfoKeyA” ( _ByVal hKey As Long, _

ByVal lpClass As String, _lpcbClass As Long, _lpReserved As Long, _lpcSubKeys As Long, _lpcbMaxSubKeyLen As Long, _lpcbMaxClassLen As Long, _lpcValues As Long, _lpcbMaxValueNameLen As Long, _lpcbMaxValueLen As Long, _lpcbSecurityDescriptor As Long, _lpftLastWriteTime As FILETIME) As LongParameters hKey—Long Integer: The handle of an open key, or one of the hive

constants listed earlier

lpClass—String: A null-terminated variable that will be loaded withthe class name for the key This can be vbNullString

Appendix I: Windows Registry Information

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 996

Trang 5

lpcbClass—Long Integer: A variable that you load with the length

of lpClass(including the terminating Null character) When the tion returns, this variable contains the number of characters actuallyloaded into lpClass

func-lpReserved—Long Integer: This is a reserved parameter Set it tozero

lpcSubKeys—Long Integer: A variable that will be loaded with thenumber of subkeys under the selected key

lpcbMaxSubKeyLen—Long Integer: A variable that will be loadedwith the length of the longest subkey under the selected key, excludingthe terminating Null character

lpcbMaxClassLen—Long Integer: A variable that will be loadedwith the length of the longest class name for the subkeys under theselected key, excluding the terminating Null character

lpcValues—Long Integer: A variable that will be loaded with thenumber of values for the selected key

lpcbMaxValueNameLen—Long Integer: A variable that will beloaded with the length of the longest value name for the subkeys underthe selected key, excluding the terminating Null character

lpcbMaxValueLen—Long Integer: A variable that will be loadedwith the buffer size required to hold the largest value data for this key.lpcbSecurityDescriptor—Long Integer: A variable that will beloaded with the length of the selected key’s Security Descriptor Whenthe function returns, this variable contains the number of bytes actuallyloaded into pSecurityDescriptor

lpftLastWriteTime—FILETIME: A user-defined Type that will tain the last time that the specified subkey was modified

con-Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegQueryKeyFlagsDescription Retrieves key flags that are set for the specified Registry key Requires

Windows Vista or later

Declaration Private Declare Function RegQueryKeyFlags _

Lib “advapi32.dll” ( _ByVal hKey As Long, _ByVal dwAttribMask As Long, _pdwAttribute As Long) As Long

997

Appendix I: Windows Registry Information

Table continues on the next page

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 997

Trang 6

Parameters hKey — Long Integer: Handle of the open key, or one of the hive

con-stants listed earlier

dwAttribMask — Long Integer: Combine one or more KEY_FLAG_stants to specify which attribute values to query You can find these con-stants at the end of this appendix

con-pdwAttribute — Long Integer: Returns the attribute mask for thespecified key

Return Value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegQueryReflectionKey

Description Determines whether Registry reflection is enabled for the specified key

Requires Windows XP Professional x64 Edition or Windows Vista orlater

Declaration Declare Function RegQueryReflectionKey _

Lib “advapi32.dll” ( _ByVal hBase As Long, _bIsReflectionDisabled As Long) As LongParameters hBase — Long Integer: Handle to the Registry key to query

bIsReflectionDisabled — Long Integer: A value that determineswhether Registry reflection is enabled or disabled for the specified key.Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegQueryValueEx

Description Retrieves both the type and the value for the specified key This is a more

sophisticated function that RegQueryValue, and is recommended foruse on Win32

Declaration Declare Function RegQueryValueEx _

Lib “advapi32.dll” _Alias “RegQueryValueExA” ( _ByVal hKey As Long, _

ByVal lpValueName As String, _ByVal lpReserved As Long, _lpType As Long, _

lpData As Any, _lpcbData As Long) As Long

Appendix I: Windows Registry Information

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 998

Trang 7

Parameters hKey—Long Integer: Handle of an open key, or one of the hive

con-stants listed earlier

lpValueName—String: Name of the value to retrieve

lpReserved—Long Integer: A reserved parameter Set it to zero lpType—Long Integer: Key value type (from the constants listed ear-lier)

lpData—Any: A buffer that is loaded with the data for the specifiedvalue

lpcbData—Long Integer: A variable that is loaded with the length oflpData When the function returns, this variable contains the number ofbytes actually loaded into lpData

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegReplaceKeyDescription Replaces a subkey with information contained in a file, and creates a

backup of the original subkey

Declaration Declare Function RegReplaceKey _

Lib “advapi32.dll” _Alias “RegReplaceKeyA” ( _ByVal hKey As Long, _ByVal lpSubKey As String, _ByVal lpNewFile As String, _ByVal lpOldFile As String) As LongParameters hKey—Long Integer: Handle of an open key, or one of the hive con-

stants listed earlier

lpValueName—String: Name of the subkey to replace This subkeymust be directly under HKEY_LOCAL_MACHINEor HKEY_USERS.lpNewFile—String: Name of the file (created using RegSaveKey) thatcontains the information with which to replace the selected subkey

lpOldFile—String: Name of the file to which the existing subkeywill be backed up

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

999 Appendix I: Windows Registry Information47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 999

Trang 8

Description Restores a subkey with information contained in a file

Declaration Declare Function RegRestoreKey _

Lib “advapi32.dll” _Alias “RegRestoreKeyA” ( _ByVal hKey As Long, _ByVal lpFile As String, _ByVal dwFlags As Long) As LongParameters hKey—Long Integer: The handle of an open key to restore from disk,

or one of the hive constants listed earlier

lpFile — String: Name of the file that contains the information torestore

dwFlags — Long Integer: Use zero for a regular restore UseREG_WHOLE_HIVE_VOLATILEfor a temporary restore (which is not saved when the system is restarted), in which case, hKeymust point toHKEY_LOCAL_MACHINEor HKEY_USERS

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegSaveKey

Description Saves a key and all its subkeys to a disk file

Declaration Declare Function RegSaveKey Lib “advapi32.dll” _

Alias “RegSaveKeyA” ( _ByVal hKey As Long, _ByVal lpFile As String, _lpSecurityAttributes As SECURITY_ATTRIBUTES) _

As LongParameters hKey — Long Integer: Handle of an open key, or one of the hive con-

stants listed earlier

lpFile — String: Name of the file into which the key (and its subkeys)will be saved

lpSecurityAttributes — SECURITY_ATTRIBUTES: A user-defined Typethat defines the security attributes for this key Security attributes arequite a complex subject and most of their features only work on Windows

NT In any case, they are rarely used, so the examples provided at the end

of this chapter re-declare this parameter ByVal SecurityAttributesasLong, and pass a Null (0&) For more information about security, refer tothe Microsoft Win32 SDK

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

Appendix I: Windows Registry Information

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1000

Trang 9

RegSaveKeyExDescription Saves the specified key and its subkeys and values to a file in the speci-

fied format

Declaration Private Declare Function RegSaveKeyEx _

Lib “advapi32.dll” _Alias “RegSaveKeyExA” ( _ByVal hKey As Long, _ByVal lpFile As String, _lpSecurityAttributes As SECURITY_ATTRIBUTES, _ByVal Flags As Long) As Long

Parameters hkey — Long Integer: Handle of an open key, or one of the hive

con-stants listed earlier

lpFile — String: Name of the file into which the key (and its subkeys)will be saved

lpSecurityAttributes — SECURITY_ATTRIBUTES: A user-defined Typethat defines the security attributes for this key Security attributes arequite a complex subject and most of its features only work on Windows

NT In any case, they are rarely used, so the examples provided at the end

of this chapter re-declare this parameter ByVal SecurityAttributesasLong, and pass a Null (0&) For more information about security, refer tothe Microsoft Win32 SDK

Flags — Long Integer: The format used to save the key or hive

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegSetKeyFlagsDescription Sets or clears Registry key flags on the specified key Requires Windows

Vista or later

Declaration Private Declare Function RegSetKeyFlags _

Lib “advapi32.dll” ( _ByVal hKey As Long, _ByVal dwAttribMask As Long, _ByVal dwAttribute As Long) As LongParameters hKey — Long Integer: Handle of the open key, or one of the hive con-

stants listed earlier

dwAttribMask — Long Integer: Combine one or more KEY_FLAG_stants to specify which attribute values to set for the key You can findthese constants at the end of this appendix

con-dwAttribute — Long Integer: Combine one or more KEY_FLAG_stants to set the value for the key Pass zero to clear the specified attributes.Return value Long Integer: Zero (ERROR_SUCCESS) on success

con-All other values are the specific error code

1001 Appendix I: Windows Registry Information47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1001

Trang 10

Description Sets the security information for the specified key

Declaration Declare Function RegSetKeySecurity _

Lib “advapi32.dll” ( _

ByVal hKey As Long, _ByVal SecurityInformation As Long, _pSecurityDescriptor As SECURITY_DESCRIPTOR) _

As LongParameters hKey — Long Integer: Handle of a key, or one of the hive constants

All other values are the specific error code

RegSetKeyValue

Description Sets a value in the specified Registry key and subkey Requires Windows

Vista or later

Declaration ‘ String declaration of lpData

Private Declare Function RegSetKeyValueString _Lib “advapi32.dll” _

Alias “RegSetKeyValueA” ( _ByVal hKey As Long, _ByVal lpSubKey As String, _ByVal lpValueName As String, _ByVal dwType As Long, _

ByVal lpData As String, _ByVal cbData As Long) As Long

‘ Numeric declaration of lpDataPrivate Declare Function RegSetKeyValueLong _Lib “advapi32.dll” _

Alias “RegSetKeyValueA” ( _ByVal hKey As Long, _ByVal lpSubKey As String, _ByVal lpValueName As String, _ByVal dwType As Long, _

lpData As Long, _ByVal cbData As Long) As Long

Appendix I: Windows Registry Information

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1002

Trang 11

Parameters hKey — Long Integer: Handle of the open key, or one of the hive

con-stants listed earlier

lpSubKey — String: Name of a subkey under the key specified in hKey.May also be vbNullString

lpValueName — String: Name of the value to set Set this tovbNullStringto set the (default) value for the key

dwType — Long Integer: The value type from the list of data types in the

“Windows Registry Data Types” section, at the beginning of this appendix lpData — String or Long Integer: The data to set in the value.cbData — Long Integer: Size of the data in bytes Use the Lenfunction

to pass the length of a String

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegSetValueExDescription Sets the value for the specified key A more sophisticated function than

RegSetValue, and is recommended for use on Win32

Declaration Declare Function RegSetValueEx _

Lib “advapi32.dll” _Alias “RegSetValueExA” ( _

ByVal hKey As Long, _ByVal lpValueName As String, _ByVal Reserved As Long, _ByVal dwType As Long, _lpData As Any, _

ByVal cbData As Long) As LongParameters hKey — Long Integer: Handle of an open key, or one of the hive con-

stants listed earlier

lpSubKey — String: Name of the subkey whose value is to be set To setthe (Default) value, specify vbNullString If the value does not exist, it

is created

Reserved — Long Integer: A reserved parameter Set it to zero

dwType — Long Integer: REG_SZ.lpData — Any: Data to be written to the specified key

1003

Appendix I: Windows Registry Information

Table continues on the next page

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1003

Trang 12

cbData — Long Integer: A variable that you load with the length oflpData, including the terminating Null character when used withREG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ.

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

RegUnloadKey

Description Unloads the specified key and all its subkeys

Declaration Declare Function RegUnLoadKey Lib “advapi32.dll” _

Alias “RegUnLoadKeyA” ( _ByVal hKey As Long, _ByVal lpSubKey As String) As LongParameters hKey — Long Integer: HKEY_LOCAL_MACHINE, HKEY_USERS, or the

handle of a key returned by the RegConnectRegistryfunction

lpSubKey — String: Name of the subkey (loaded using theRegLoadKey function) to unload

Return value Long Integer: Zero (ERROR_SUCCESS) on success

All other values are the specific error code

Registr y API Constant and User-Defined

Type Declarations

To help you with this book, and so that you won’t have to go searching for them, the following is a list ofall the Constant and User-Defined Type declarations you’ll need when using the Registry APIs

‘Key declarations

Const HKEY_CLASSES_ROOT As Long = &H80000000

Const HKEY_CURRENT_CONFIG As Long = &H80000005

Const HKEY_CURRENT_USER As Long = &H80000001

Const HKEY_DYN_DATA As Long = &H80000006

Const HKEY_LOCAL_MACHINE As Long = &H80000002

Const HKEY_PERF_ROOT As Long = HKEY_LOCAL_MACHINE

Const HKEY_PERFORMANCE_DATA As Long = &H80000004

Const HKEY_USERS As Long = &H80000003

‘Parameter declarations

Const REG_NOTIFY_CHANGE_ATTRIBUTES As Long = &H2

Const REG_NOTIFY_CHANGE_LAST_SET As Long = &H4

Const REG_NOTIFY_CHANGE_NAME As Long = &H1

Const REG_NOTIFY_CHANGE_SECURITY As Long = &H8

Const REG_CREATED_NEW_KEY As Long = &H1

Appendix I: Windows Registry Information

47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1004

Trang 13

Const REG_OPTION_BACKUP_RESTORE As Long = &H4Const REG_OPTION_VOLATILE As Long = &H1Const REG_OPTION_NON_VOLATILE As Long = &H0Const STANDARD_RIGHTS_ALL As Long = &H1F0000

Const SYNCHRONIZE As Long = &H100000Const READ_CONTROL As Long = &H20000Const STANDARD_RIGHTS_READ As Long = (READ_CONTROL)Const STANDARD_RIGHTS_WRITE As Long = (READ_CONTROL)Const KEY_CREATE_LINK As Long = &H20

Const KEY_CREATE_SUB_KEY As Long = &H4Const KEY_ENUMERATE_SUB_KEYS As Long = &H8Const KEY_NOTIFY As Long = &H10

Const KEY_QUERY_VALUE As Long = &H1Const KEY_SET_VALUE As Long = &H2

Const KEY_READ As Long = (( _STANDARD_RIGHTS_READ _

Or KEY_QUERY_VALUE _

Or KEY_ENUMERATE_SUB_KEYS _

Or KEY_NOTIFY) _And (Not SYNCHRONIZE))

Const KEY_WRITE As Long = (( _STANDARD_RIGHTS_WRITE _

Or KEY_SET_VALUE _

Or KEY_CREATE_SUB_KEY) _And (Not SYNCHRONIZE))

Const KEY_EXECUTE As Long = (KEY_READ)

Const KEY_ALL_ACCESS As Long = (( _STANDARD_RIGHTS_ALL _

REG_PROCESS_APPKEY = &H1REG_MUI_STRING_TRUNCATE = &H1

‘Key value typesConst REG_BINARY As Long = 3Const REG_DWORD As Long = 4Const REG_DWORD_BIG_ENDIAN As Long = 5Const REG_DWORD_LITTLE_ENDIAN As Long = 4Const REG_EXPAND_SZ As Long = 2

Const REG_LINK As Long = 6Const REG_MULTI_SZ As Long = 7Const REG_NONE As Long = 0Const REG_RESOURCE_LIST As Long = 8Const REG_QWORD As Long = 11

1005 Appendix I: Windows Registry Information47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1005

Trang 14

Const REG_QWORD_LITTLE_ENDIAN As Long = 11Const REG_SZ As Long = 1

‘API return codes

Const ERROR_ACCESS_DENIED As Long = 5&

Const ERROR_BADDB As Long = 1009&

Const ERROR_BADKEY As Long = 1010&

Const ERROR_CANTOPEN As Long = 1011&

Const ERROR_CANTREAD As Long = 1012&

Const ERROR_CANTWRITE As Long = 1013&

Const ERROR_INSUFFICIENT_BUFFER As Long = 122&Const ERROR_INVALID_HANDLE As Long = 6&

Const ERROR_INVALID_PARAMETER As Long = 87&Const ERROR_KEY_DELETED As Long = 1018&

Const ERROR_KEY_HAS_CHILDREN As Long = 1020&Const ERROR_MORE_DATA As Long = 234&

Const ERROR_NO_MORE_ITEMS As Long = 259&

Const ERROR_OUTOFMEMORY As Long = 14&

Const ERROR_REGISTRY_CORRUPT As Long = 1015&Const ERROR_REGISTRY_IO_FAILED As Long = 1016&Const ERROR_REGISTRY_RECOVERED As Long = 1014&Const ERROR_SUCCESS As Long = 0&

‘Platform specific view of the Registry

Const KEY_WOW64_32KEY As Long = &H200

Const KEY_WOW64_64KEY As Long = &H100

‘Registry restriction flags

Const RRF_RT_ANY As Long = &HFFFF

Const RRF_RT_DWORD As Long = &H18

Const RRF_RT_QWORD As Long = &H48

Const RRF_RT_REG_BINARY As Long = &H8

Const RRF_RT_REG_DWORD As Long = &H10

Const RRF_RT_REG_EXPAND_SZ As Long = &H4

Const RRF_RT_REG_MULTI_SZ As Long = &H20

Const RRF_RT_REG_NONE As Long = &H1

Const RRF_RT_REG_QWORD As Long = &H40

Const RRF_RT_REG_SZ As Long = &H2

Const RRF_NOEXPAND As Long = &H10000000

Const RRF_ZEROONFAILURE As Long = &H20000000

‘Registry key flags

Const KEY_FLAG_DISABLE_REDIRECTION As Long = &H10Const KEY_FLAG_EXEMPT_REFLECTION As Long = &H4Const KEY_FLAG_OWNERSHIP_REFLECTION As Long = &H8

‘Registry format flags

Const REG_STANDARD_FORMAT As Long = &H1

Const REG_LATEST_FORMAT As Long = &H2

Const REG_NO_COMPRESSION As Long = &H4

‘SECURITY_INFORMATION constants

Const OWNER_SECURITY_INFORMATION As Long = &H1

Appendix I: Windows Registry Information47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1006

Trang 15

Const GROUP_SECURITY_INFORMATION As Long = &H2Const DACL_SECURITY_INFORMATION As Long = &H4Const SACL_SECURITY_INFORMATION As Long = &H8Const UNPROTECTED_SACL_SECURITY_INFORMATION As Long = &H10000000Const UNPROTECTED_DACL_SECURITY_INFORMATION As Long = &H20000000Const PROTECTED_SACL_SECURITY_INFORMATION As Long = &H40000000Const PROTECTED_DACL_SECURITY_INFORMATION As Long = &H80000000

‘User-defined TypesType SECURITY_ATTRIBUTESnLength As LonglpSecurityDescriptor As LongbInheritHandle As LongEnd Type

Type FILETIMEdwLowDateTime As LongdwHighDateTime As LongEnd Type

Type ACLAclRevision As ByteSbz1 As ByteAclSize As IntegerAceCount As IntegerSbz2 As IntegerEnd Type

Type SECURITY_DESCRIPTORRevision As ByteSbz1 As ByteControl As LongOwner As LongGroup As LongSacl As ACLDacl As ACLEnd Type

1007 Appendix I: Windows Registry Information47033bapp09.qxd:WroxProgRef 3/30/07 12:30 AM Page 1007

Trang 17

Access Wizards, Builder s,

Access Wizards

As you can tell from the extensive list of enhanced wizards, Access is more user-friendly and automated with each version The following table describes 57 wizards, including 11 that werereplaced or removed from Access 2007 The status column indicates changes between Access 2003and 2007 Although there is some overlap, the main difference between enhanced and improved isthat enhanced is used to denote changes to the wizard including the user interface while improveddenotes that the target feature/process — such as the import or export process — has improved.The Replaced status indicates that, although the particular wizard is no longer available, its func-tion is provided elsewhere, as explained in the description

47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1009

Trang 18

Wizard Description Status

AutoDialer Adds an AutoDialer to a control on a form,

datasheet, or toolbar It incorporates modeminformation and dials the number

Enhanced so that the dialer function can be calledfrom an embedded macroinstead of using VBA.AutoForm The AutoForm was replaced by the selection of

auto-forms available in the Forms group of the ate tab, as shown in Figure J-1 Any of theforms are automatically created based on theselected record source The traditional formwizard is also available

cre-Replaced

AutoFormat Applies a predefined style and format to a

form or report, and allows creation of customstyles This has been enhanced by additionalauto formats (displayed as styles in the Formand Report wizards)

Enhanced with additionalformats

AutoPage DAPs cannot be created in Access 2007 so this

wizard is no longer needed In prior versions, itcreates a data access page that can be used onthe Web or intranet A DAP can also get datafrom other sources, such as Excel

Removed

AutoReport Replaced by the selection of reports available in

the Reports group of the create tab, as shown inFigure J-1 These reports are automatically cre-ated based on the selected record source Thetraditional report wizard is also available

Replaced

Chart/Graph Adds a chart to a form or report based on the

data in a table or query

New

Combo Box Creates a combo box control on a form This

has additional options and now defaults to useembedded macros for the ACCDB file format

Enhanced to use ded macros for theACCDB format

embed-Command Button Creates a command button control on a form Enhanced to use

embed-ded macros for the ACCDBformat There have alsobeen changes to some ofthe VBA commands to be

in concert with the newcontrols such as the RibbonAppendix J: Access Wizards, Builders, and Managers

47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1010

Trang 19

Table continues on the next page

Conflict Resolver Resolves conflicts between replicated databases

at synchronization time Works with 2000 and2002-2003 format MDB files

Unchanged

Create Outlook Task Creates an Outlook Task and includes the

details of the process, how to initiate it, and theassociated objects and destination locations

Outlook allows these to be recurring tasks

New

Crosstab Query Creates a query that summarizes data in a

compact, spreadsheet-like format

Unchanged

Database Created databases for a variety of uses

Replaced by custom templates in 2007

Replaced by templates

Database Splitter Splits databases into data and interface

por-tions, so that one or more users can have localcopies of the interface connected to the data on

a server Text added to address database words

pass-Unchanged

Documenter Generates an Access report that displays the

design characteristics of database objects,including the tables, queries, forms, reports,macros, modules, and attachments

Enhanced to handle plex data types

com-Export Text Exports data to a text file and allows

specifica-tions to be saved It can also be added toOutlook as a Task Text export is improved

Improved to allow uling an Outlook Task

sched-Export to WindowsSharePoint Services

Exports to Windows SharePoint Services There

is added functionality to work with ments and multi-value fields As with otherimport and export processes, the specificationscan be saved and reused or modified

attach-Improved to date complex data types

accommo-Find DuplicatesQuery

Creates a query that finds records that haveduplicate field values and are in a single table

or query

Unchanged

Find UnmatchedQuery

Creates a query that finds records in one tablethat have no related records in another table

Unchanged

Form Creates a new form based on the pre-selected

record source The basic form wizard isunchanged, but it now offers more than 20styles (aka AutoFormats) to select from TheForms group on the Create tab allows user tocreate specific types of forms, such as a SplitForm or a PivotChart

Improved

1011 Appendix J: Access Wizards, Builders, and Managers47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1011

Trang 20

Wizard Description Status

Import HTML Imports HTML tables and lists from an Internet

or intranet site into an Access table A greatway to start building interfaces with Web-based databases Importing is improved

Improved import

Import from

Windows

SharePoint Services

Imports from Windows SharePoint Services Improved to

accommo-date complex data types

Import Spreadsheet Imports a Microsoft Excel or other spreadsheet

into a Microsoft Access table Significantenhancements, including ability to specify fieldtypes Can also be scheduled as an Outlook Task

Enhanced Import

Import Text Imports a text file into a Microsoft Access table

Importing is improved and it now allowsscheduling as an Outlook Task

Links an Exchange or Outlook folder to a table

in a Microsoft Access database

Unchanged

Link HTML Links an HTML table or list on the Internet or

an intranet to a Microsoft Access table

Unchanged

Link to Windows

SharePoint Services

Links to Windows SharePoint Services list

Linking will accommodate complex data types

2007 does not allow linking to a view of aSharePoint list

Improved to date complex data types

accommo-Link Spreadsheet Links spreadsheet data to a Microsoft Access

table Can pull in SmartTags The wizard isunchanged, but the process benefits fromimprovements to importing

Improved

Link Table Linked to tables in Access projects Now

replaced with features in the new ribbon’sExternal Data tab

Replaced

Link Text Links a text file to a Microsoft Access table The

wizard is unchanged, although the processbenefits from improvements in data typerecognition and can be scheduled as an

Improved

Appendix J: Access Wizards, Builders, and Managers

47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1012

Trang 21

Table continues on the next page

List Box Creates a list box control on a form, now

includes sort options

Enhanced

Lookup Creates a lookup column in a table, which

dis-plays a list of values the user can choose from

Includes a sort option Enhanced to supportcomplex data

Enhanced

Macro To ModuleConverter

Converts macros to Visual Basic code, ing saved macros as well as embedded macros

includ-on forms and reports Enhanced with newmacro actions and now supports TempVars

Enhanced

Microsoft SQLServer Database

Creates a new Microsoft SQL Server Databaseconnected to a new Microsoft Access project

Unchanged

Microsoft WordMail Merge

Uses an Access table or query as the recordcourse for Microsoft Word letters and e-mails

The wizard can be found in the Export group

of the Ribbon’s External Data tab by clicking

on More to see the last item in the down list

drop-Unchanged

Move To SharePointSite

Simultaneously moves the data from all thetables, maintains the relationships, and man-ages the complex data types

New

Option Group Creates a group of option buttons on a form Unchanged

Page Created new data access pages, allowing

dis-tinct recordsource determination DAPs cannot

be created in Access 2007 so this wizard is nolonger needed

Removed

Page Combo Box Created a drop-down control on a data access

page DAPs cannot be created in Access 2007 sothis wizard is no longer needed

Removed

Page CommandButton

Created a command button control on a dataaccess page DAPs cannot be created in Access

2007 so this wizard is no longer needed

Removed

Page List Box Created a list box control on a data access page

DAPs cannot be created in Access 2007 so thiswizard is no longer needed

Removed

Partial Replica Creates or modifies a partial replica Builds a

replica that contains only a subset of the recordsthat a full replica would have In Access 2007,this is used only by the MDB file format

Unchanged

1013 Appendix J: Access Wizards, Builders, and Managers47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1013

Trang 22

Wizard Description Status

Performance

Analyzer

Analyzes the efficiency of a database and duces a list of suggestions for improving itsperformance

pro-Unchanged

PivotTable Places a Microsoft Excel PivotTable on a

Microsoft Access form PivotTables andPivotCharts are now optional views for tables,queries, forms, views, and stored procedures

New

Print Relationships Creates a report that diagrams the relationships

in a Microsoft Access database

Unchanged

Report Creates a report based on a table or query

The basic report wizard is unchanged; however

it now offers more than 20 styles (akaAutoFormats) to choose from

Links fields in a main form and a subform or in

a main report and a subreport, based on sharedfields or established relationships

Unchanged

Table Table and Field Templates replace this wizard

for creating a new table

Replaced

Table Analyzer Takes a table with a lot of duplicate data and

splits it into related tables for more efficientstorage

Unchanged

Upsizing Upsizes a Microsoft Access database to a

Microsoft SQL Server database

Unchanged

User-Level Security In Access 2007, this is available only with the

MDB file format Based on the existing base, the wizard creates a new, encoded data-base that controls user access and permissions

data-It also leaves an unsecured backup copy of thedatabase

Unchanged.Appendix J: Access Wizards, Builders, and Managers

47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1014

Trang 23

Access Builder sAccess 2007 offers nine builders that will guide developers through a process You’re familiar with theQuery Builder There are also some builders, such as the Color Builder, that are available in other Officeprograms In Access 2007, the Field Builder is replaced by table templates and the Color Builder isenhanced to provide the color picker used by other programs.

Builder Description

Color Enhanced to use the color picker used by other programs In addition

to a larger selection of color swatches, it also displays a palette forselecting customized colors

Edit List Items Builds and edits value lists that are the row source for combo box

and list box controls or for lookup fields in tables

Expression Creates expressions for macros, queries, and property sheets

Field Creates fields in tables in previous versions Replaced by table

tem-plates in Access 2007

Macro Creates and edits macros, such as those created when a command

button is added to a form or report Builds both embedded andstandalone macros

ODBC Connection String Creates the correct syntax for a connection to an ODBC database

Walks users through the process to establish a connection to an nal data source

exter-Picture Creates bitmap images for forms and reports

Query Creates the correct syntax for a query

Smart Tags Displays a list of available smart tags and their actions Smart tags

enable you to perform tasks within Access that you otherwise wouldhave needed to open other programs to handle Smart tags can beattached to a file in a table or a query or to controls on a form, report,

or data access page

Access Manager s

In addition to builders and wizards, Access has five very powerful managers Granted, there are timesthat it works well to create your own tools or use add-ins to provide these functions, but for the mostpart, the managers do an incredible job The beauty of managers is that they work right out of the box.They are quick and easy to use, and they provide consistency There are no changes to the managers inAccess 2007, so if you’ve been using the managers, they will be like old friends

1015 Appendix J: Access Wizards, Builders, and Managers47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1015

Trang 24

Manager Description Location

Add-In In addition to installing and

unin-stalling wizards, builders, and ins, the Add-In Manager helpscreate wizards and helps you toinstall your own add-ins

add-Database Tools Ribbon tab; selectAdd-ins in the Database Tools group

Linked Table Allows linking and changing links

to tables in external databases aswell as through some ODBC con-nections, such as with Excel

Database Tools Ribbon tab; selectLinked Table Manager in theDatabase Tools group

Manage Data

Collection Messages

Tracks the status and allowschanges to settings of e-mails usedfor data collections Allows mes-sages to be resent or deleted

External Data ribbon tab, on CollectData, click Manage Replies

Manage Data Tasks View and manage saved import

and export specifications Allowschanges to general aspects such asthe specification name and filepath, but does not allow changes todetails, such as the tables, fields,and worksheets Can create anOutlook Task

External Data Ribbon tab; click eitherthe Saved Imports or the SavedExports button

Switchboard Creates and manages switchboard

forms for applications

Database Tools Ribbon tab; selectSwitchboard Manager in the DatabaseTools group

Appendix J: Access Wizards, Builders, and Managers

47033bapp10.qxd:WroxProgRef 3/30/07 12:30 AM Page 1016

Trang 25

Reser ved Words and Special Character s

There are numerous words that should not be used to name fields, objects, and variables For the

most part, these are called reserved words Reserved words have a specific meaning to Microsoft

Access, the Jet database engine, and the new Access database engine (ACE) We also list reservedwords that have specific meaning to SQL Server or ODBC drivers Depending on how your appli-cation interfaces with other programs, it may be prudent to avoid using words that have specificprogrammatic meanings to those as well If you want to start a list of reserved words, begin withthe list of all the properties of database objects, all Visual Basic keywords, and all third-party anduser-defined names and functions

Access 2007 creates an error message when select reserved words are used as field names For themost part, however, using reserved words often creates error messages that do not indicate thesource of the problem For example, it is far from intuitive that the following error message:The wizard was unable to preview your report, possibly because

a table needed by your report is exclusively locked

may have been triggered by the use of a reserved word Consequently, a developer may sarily spend time troubleshooting the wrong problem When you are working with an applicationthat uses reserved words, particularly as the name of tables or fields, rename the database objects

unneces-if it is at all possible and feasible to do so If it isn’t possible to rename them, then be sure toenclose the names in brackets when they are called in code or in queries Here’s an example show-ing the name of the table in brackets because the term tableNameis a reserved word:

Trang 26

merely changing the syntax to use Me!(bang) instead of Me.(dot) will allow the code to compile Youcannot avoid the problem simply by not compiling the code, because that merely ensures that the codewill break and stop the application from running.

Figure K-1

We recommend that you develop the practice of debugging promptly after making changes to any code This enables you to catch errors promptly and prevent them from being repeated or compounding.Considering all the things that can go wrong, and the propensity for something to go wrong at the worsttimes, why tempt fate by not doing everything you can to ensure that your code will run smoothly?Additionally, search and replace utilities such as Speed Ferret are designed to find and replace theoffending word(s) throughout the application, including the code project or VBA In the past, a couple ofproducts were consistently recommended by developers, but it will likely be a while before similar toolsare released for the new file format The Access news groups and MVP sites are great resources for learn-ing about these types of tools Some are free, but even a purchased program typically pays for itself withits first use

It is clear that if reserved words are causing a problem with a database, it is worth enforcing namingconventions Implementing a comprehensive naming policy can help you avoid most of the problemsassociated with reserved words Appendix L discusses some of the well-accepted naming conventions

What Are the Sources of Reser ved Words?

In addition to the lists of reserved words that are directly associated with Access, ACE, and Visual Basic,there are also words that have special meaning to ActiveX Data Objects (ADO), OLE DB, Open DatabaseConnectivity (ODBC), and any DLL (dynamic-link library) referenced in your application These, too,should be treated as reserved words for your application Just by setting a reference to a type library, anobject library, or an ActiveX control, all the reserved words for the referenced items become reservedwords for the Access application And the list keeps growing because built-in function names and user-defined names also become reserved words As you create interfaces to work with other programs anddevelopment languages, such as SharePoint, Excel, and NET, you will want to be cautious about theirreserved words as well

It can get even hairier The reserved words for a given application vary depending on what mode theACE is running in This is determined by whether ACE is called from Microsoft Access, the MicrosoftOLE DB Provider for ACE, a Data Access Object, or the Microsoft Access ODBC driver Whether ACE isrunning in ANSI mode or non-ANSI (traditional) mode also has an effect on the list, such that a querythat works under one scenario may fail when the database application is opened in a different mode.Appendix K: Reserved Words and Special Characters

47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1018

Trang 27

You can find lists of reserved words by using the online help feature in Access, by searching for reservedwords on the Internet, and by pouring through reference books Regretfully, no list will be comprehen-sive or tailored to your needs and interfaces Even the lists published by authoritative sources cannot beassumed to be complete This is another obvious endorsement for implementing naming conventions.The potential lists of reserved words can seem a bit overwhelming That is why this appendix not onlycontains a table of reserved words but also lists some of the words that we think should have beenincluded in the original lists The table is a compilation of words from a variety of sources, including thereserved words for ANSI mode, and should significantly reduce your research time Please keep in mindthat it is not an exhaustive list and that it does not include additional words associated with third-partyadd-ins Allen Browne’s Access MVP website (http://allenbrowne.com/AppIssueBadWord.html)has a compilation of reserved words that generously includes the source, such as SQL, Access, Jet, and

so forth Allen also offers a utility that will check your application for usage of reserved words

Reser ved Words with Er ror MessagesYou might wonder why you can’t simply use a tool that will check against your custom list of reservedwords and give you a timely and specific error message as you are creating your tables and addingfields Although that seems like a great idea, it wouldn’t be easy to implement The Access team recog-nizes the merit in the concept, though, and has instituted an automatic check for a limited number ofterms that are commonly used in both VBA and as field names At this time, the list contains only sixwords:

Nonetheless, the seed has been planted, so to speak

Keep in mind that you might circumvent this built-in check if you are creating a table in code Accessperforms the check and generates the appropriate error message when you are creating a new table inthe Access UI (see Figure K-2) However, you won’t trigger the error if you create a table usingCreateTableDefor the CREATE TABLEstatement

Figure K-2

Reser ved Word List

If you’re ambitious, you might be tempted to try to compile your own list of reserved words by ing lists from the most common sources Be aware, however, that some of the lists were incomplete

combin-1019 Appendix K: Reserved Words and Special Characters47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1019

Trang 28

when initially published, and that additional words should be included in the lists as new objects oractions are added Given those caveats, you’d still want a list that is a compilation of words from Access,ACE, MS Query SQL, and ANSI-92.

In the past, there were two lists, but with the ease of integration, there’s no longer differentiationbetween Access reserved words and those from other sources Of course, it is perfectly understandable

to prefer to work against Access’s list of 200+ terms instead of the compiled list of more than 500 wordsand terms Searching Access help for Reserved Words leads you to an explanation and list of Accessreserved words and the list of words that should not be used as identifiers So you’re already checkingtwo sources, and there are still the lists of special characters and ASCII characters and their names

As you can see, there is no easy way to consolidate everything into one tidy list, especially if there is anyhope of understanding why you should avoid certain words and characters or knowing how to usethem So you’re still stuck with multiple lists: the compilation of words to avoid (reserved words) andthe lists of special characters and other ASCII characters

Following is the list of words and terms that are reserved by Access or by programs and languages monly used with Access We’ve included a few words that have been reported to cause problems, so thatyou can avoid using them, too

com-ABSOLUTE ACTION ACK

ADD ALLOCATE ALPHANUMERIC

ALTER ALTER TABLE AND

ANY APPLICATION ARE

AS ASC ASSERTION

ASSISTANT AT AUTHORIZATION

AUTOINCREMENT AVG BAND

BEGIN BEL BETWEEN

BINARY BIT BIT_LENGTH

BNOT BOOLEAN BOR

BOTH BS BXOR

BY BYTE CAN

CASCADE CASCADED CASE

CAST CATALOG CHAR

CHAR_LENGTH CHARACTER CHARACTER_LENGTH

CHECK CLOSE CLUSTERED

COALESCE COLLATE COLLATION

COLUMN COMMIT COMP

COMPACTDATABASE COMPRESSION CONNECT

CONNECTION CONSTRAINT CONSTRAINTS

CONTAINER CONTAINS CONTINUE

CONVERT CORRESPONDING COUNT

COUNTER CRCREATE CREATEDATABASE

CREATEDB CREATEFIELD CREATEGROUP

CREATEINDEX CREATEOBJECT CREATEPROPERTY

CREATERELATION CREATETABLEDEF CREATEUSER

CREATEWORKSPACE CROSS CURRENCY

CURRENT CURRENT_DATE CURRENT_TIME

CURRENT_TIMESTAMP CURRENT_USER CURRENTUSER

CURSOR DATABASE DATE

DATETIME DAY DC1

DC2 DC3 DC4

Appendix K: Reserved Words and Special Characters

47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1020

Trang 29

DEALLOCATE DEC DECIMALDECLARE DEFAULT DEFERRABLEDEFERRED DELETE DESCDESCRIBE DESCRIPTION DESCRIPTORDIAGNOSTICS DISALLOW DISCONNECTDISTINCT DISTINCTROW DLEDOCUMENT DOMAIN DOUBLEDROP ECHO ELSE

EM END END-EXECENQ EOT EQVERROR ESC ESCAPEETB ETX EXCEPTEXCEPTION EXCLUSIVECONNECT EXCLUSIVECONNECTEXEC EXECUTE EXISTS

EXIT EXTERNAL EXTRACTFALSE FETCH FFFIELD FIELDS FILLCACHEFIRST FLOAT FLOAT4FLOAT8 FOR FOREIGNFORM FORMS FOUNDFROM FS FULLFUNCTION GENERAL GETGETOBJECT GETOPTION GLOBAL

GO GOTO GOTOPAGEGRANT GROUP GROUP BY

GS GUID HAVINGHOUR IDENTITY IDLEIEEEDOUBLE IEEESINGLE IFIGNORE IMAGE IMMEDIATEIMP IN INDEXINDEXCREATEDB INDEXES INDICATORINHERITABLE ININDEX INITIALLYINNER INPUT INSENSITIVEINSERT INSERTTEXT INT

INTEGER INTEGER1 INTEGER2INTEGER4 INTERSECT INTERVALINTO IS ISOLATIONJOIN KEY LANGUAGE LAST LASTMODIFIED LEADINGLEFT LEVEL LEVEL* MIN

LF LIKE LOCALLOGICAL LOGICAL1 LONGLONGBINARY LONGCHAR LONGTEXTLOWER MACRO MATCHMAX MEMO MIN MINUTE MOD MODULEMONEY MONTH MOVENAK NAME NAMESNATIONAL NATURAL NCHARNEWPASSWORD NEXTNO NONCLUSTEREDNOT NOTE NTEXTNUL NULL NULLIFNUMBER NUMERIC NVARCHAROBJECT OCTET_LENGTH OFF

1021 Appendix K: Reserved Words and Special Characters47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1021

Trang 30

OFOLEOBJECT OLEOBJECT ON

ONLY OPEN OPENRECORDSETOPTION OR ORDER

ORIENTATION ORORDEROUTER OUTPUT

OVERLAPS OWNERACCESS PAD

PARAMETER PARAMETERS PARTIALPASSWORD PERCENT PIVOT

POSITION PRECISION PREPAREPRESERVE PRIMARY PRIOR

PRIVILEGES PROC PROCEDUREPROPERTY PUBLIC QUERIESQUERY QUIT READ

REAL RECALC RECORDSETREFERENCES REFRESH REFRESHLINKREGISTERDATABASE RELATION RELATIVEREPAINT REPAIRDATABASE REPLICATIONREPORT REPORTS REQUERYRESTRICT REVOKE RIGHT

RIGHT SPACE ROLLBACK ROWS

RS SCHEMA SCREEN

SCROLL SECOND SECTIONSELECT SELECTSCHEMA SELECTSECURITYSESSION SESSION_USER SET

SET SUM SETFOCUS SETOPTIONSHORT SI SINGLE

SIZE SMALLDATETIME SMALLINTSMALLMONEY SO SOH

SOME SPACE SQL

SQLCODE SQLERROR SQLSTATESTDEV STDEVP STRING

STX SUB SUBSTRINGSUM SYN SYSNAMESYSTEM_USER TAB TABLE

TABLEDEF TABLEDEFS TABLEIDTABLEID* TEMPORARY TEXT

THEN TIME TIMESTAMPTIMEZONE_HOUR TIMEZONE_MINUTE TINYINT

TO TOP TRAILINGTRANSACTION TRANSFORM TRANSLATETRANSLATION TRIM TRUE

TYPE UNION UNIQUE

UNIQUEIDENTIFIER UNKNOWN UPDATE UPDATEIDENTITY UPDATEOWNER UPDATESECURITYUPPER US USAGE

USER USING VALUE

VALUES VAR VARBINARYVARCHAR VARP VARYINGVIEW VT WHEN

WHENEVER WHERE WITH

WORK WORKSPACE WRITE

XOR YEAR YES

YESNO ZONE

Appendix K: Reserved Words and Special Characters

47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1022

Trang 31

What Are Special Character s?

Special characters are those that are interpreted by Access, SQL Server, and VBA as field type delimiters,

as the introduction of a comparison function, or other instructions Therefore, special characters and trol characters (ASCII values 0 through 31) should not be used as part of the name of a database field,object, variable, procedure, or constant (Okay, we do concede that there are different guidelines fornaming VB procedures, variables, and constants than for database objects and field names But it seemssensible to combine the two sets of rules and apply them to both situations.)

con-Looking at the list of special characters, it is obvious why some should be avoided For example, the (period) can return unexpected results when used with a reserved word For example, given a field Name

in table Students, the syntax Students.Namewould return the value of the table’s Namepropertyinstead of the value in the Namefield

Similarly, putting an apostrophe in a field name causes the VBA to choke as it interprets the single quote

as the beginning or end of a string Because the ‘is being used as an apostrophe, there is nothing toclose the string until VBA comes to the next apostrophe (which is likely meant to start another string)

In addition to the following two lists of characters to avoid, there are a couple more seemingly innocentthings that can turn into gotchas:

❑ Do not put spaces in field names For example, field names such as 2ndPhoneand Area Codecould cause unexpected hiccups If you insist on separating words, use the underscore (a grudg-ingly acceptable option)

❑ Do not start field or column names with numeric characters

Remember that an object or field name cannot begin with a space Access immediately advises you of theerror if you try to put certain special characters in a field name Figure K-3 shows the error message gener-ated by trying to create a field name with a leading space Notice, however, that Access accepted otherspecial characters within the field name This may create a false sense of well-being because, as pointedout earlier, a name containing a special character requires special treatment throughout the application

Figure K-3

Special characters not only wreak havoc in code, they can cause problems if they are

in text and memo fields Most of these special characters put the breaks on a word search An application that has been working smoothly for months may suddenly throw error messages when the user runs a search on a text field For example, Kim’s Curry House, as the name of a business will likely stop a search The apostrophe causes the SQL interpreter to “think” that a string has been initiated or ended.

Solution: Use code to prevent users from entering special characters into text and memo fields See the code example at the end of this appendix.

1023 Appendix K: Reserved Words and Special Characters47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1023

Trang 32

Special Characters to Avoid

Trang 33

ASCII Characters to Avoid

You often see the term ASCII, but its full name is seldom spelled out, so here it is in plain English:American Standard Code for Information Interchange Computers are number-driven, and ASCII code

is the numeric representation of characters or actions The first 32 ASCII characters are actions or printing characters, which is why using any of these characters as the name of an object or functionwould be interpreted as an instruction and could initiate unexpected actions Most developers recog-nize ESC, CAN, NUL, LF, CR, and TAB as commands, but many of the other ASCII characters havebeen forgotten The following table, then, has a dual purpose It’s a handy reference for knowing whatcharacters to avoid, and it’s a useful resource for when you want to include an action such as inserting

non-a cnon-arrinon-age return non-and line feed in your VBA The chnon-arnon-acter nnon-ames hnon-ave been incorpornon-ated into the list ofwords to avoid

ASCII Characters 0 Through 31

Trang 34

ASCII Characters 0 Through 31 (continued)

Bonus Code Example

It’s sometimes beneficial to prevent users from entering certain characters in data via a form By settingthe form’s KeyPreviewproperty to Yes, an event procedure can be used to essentially ignore the entry

of selected character This is accomplished by using an event procedure on the control’s OnKeyPressproperty

The following example prevents the database from entering a period, apostrophe, or ampersand in thetext box txtBusinessName

Private Sub txtBusinessName_KeyPress(KeyAscii As Integer)

Select Case KeyAscii

Case 46, 39, 38 ‘ Period, apostrophe, ampersandKeyAscii = 0

End Select

End Sub

If the user entered Kim & John’s Cafe, the table would actually store Kim Johns Cafe The specifiedASCII characters are essentially eliminated because the ASCII character 0is null (Only the character iseliminated, so unless some other code is included, this will result in two spaces between the words.) Thiscode example can be modified to fit many situations and an infinite combination of characters

Obviously, error trapping needs to be added, but it was left out here for the sake of simplicity You canuse the ASCII character numbers listed in the “Special Characters to Avoid” table earlier in the appendix

to write code that will prevent characters from being stored in the database

Appendix K: Reserved Words and Special Characters

47033bapp11.qxd:WroxProgRef 3/30/07 12:30 AM Page 1026

Trang 35

Naming Conventions

The logic of using a naming convention is about as easy to grasp as the logic of standardizing analphabet or language Both structures are intended to make communication easier In addition toproviding standards, they also allow plenty of opportunities for customization Adopting a nam-ing convention provides for consistency, can avoid conflicts with reserved words, and sets theframework for building strong code that is more easily read and interpreted by the original devel-oper (yes, you will likely forget why you wrote what you did) and by other developers You may

as well count on someone else trying to interpret your code, whether it is someone on your team,

a technical consultant, or someone who inherits your project

Using a naming convention also helps prevent conflicts due to multiple uses of the same namebecause, in most cases, a name should have only one meaning within an application

If you are new to Access or to writing code, this is the perfect time to become familiar with themost common naming conventions and to start developing your own protocols This appendixincludes some guidance for naming objects and provides tables of the most commonly acceptednames used in VBA Now that macros have come into their own, complete with error handling,the appendix also tackles their naming considerations Adopt, adapt, or create, it’s up to you.People who choose to create their own naming conventions still benefit from being familiar withstandard naming conventions After all, they still need to read and interpret code used in Accessand VBA help files, books, and sample applications, and at some point, they are likely to collabo-rate with others on some level

Why Implement Naming Conventions?

As previously indicated, the use of naming conventions is voluntary, and developers can and dowrite applications without applying (or enforcing) naming conventions However, conventionscan save a lot of time and money, and can prevent needless frustrations by making it easier andfaster to read and interpret code, whether it is code that you wrote last week or last year, or codefrom another developer

Naming conventions offer many benefits in that they are like sharing a common language.Typically, that is important if the application is shared, but it’s also essential to the individual47033bapp12v6.5.qxd 3/30/07 12:39 AM Page 1027

Trang 36

developer who has to work with a program that he hasn’t seen for a couple of years Following are some

of the most common benefits of using a naming convention:

❑ They make object names more informative so developers can quickly understand an tion’s structure and code

applica-❑ They provide a standardized vocabulary for team efforts

❑ They minimize conflicts when adding third-party products

❑ They allow code, tools, and code libraries to be shared across various VBA platforms

❑ They group objects and facilitate various sort options

❑ They can provide self-documenting program code

❑ They enhance search and replace capabilities

❑ They enable you to learn, modify, and incorporate code from others, including from magazines,reference books, the Internet, and peers

Naming conventions need to be an integral part of the basic design, and they should be fully adoptedbefore one stroke is committed to the database In addition to establishing rules for objects within yourAccess application, you also need to manage the path and filenames for objects with which your applica-tion will interface Establishing naming conventions takes a little extra time upfront, but the payoff isfast and it just keeps paying The benefits are compounded as the application grows, becomes morecomplicated, interfaces with other applications, and is used by other developers

Many developers are careful about naming tables, forms, fields, and even the controls that they build.But all too often, the controls that a wizard builds are left with their original names such as Command65

or Text58 Because those names do not indicate what the control really does, they can create confusionand unnecessary conflicts, particularly if code is added to one of the control’s events One solution is tolet the wizards do their stuff, and then promptly rename the object so that all future references to it willautomatically use the correct name Please remember that if the wizard generated the code, the name ofthe object needs to be changed both in the object’s property and in VBA That means you need to openthe VBA Editor and update the name of the control within the code created by the wizard

A Brief Histor y

Currently, the most common naming conventions used in Access applications, Microsoft product mentation, and reference books are based on the Hungarian notation That notation was created by aHungarian, Charles Simonyi, while working at Microsoft in the 1980s In the Access world, Greg

docu-Reddick and Stan Leszynski further developed and popularized the naming convention Greg publishedthe Reddick VBA (RVBA) Naming Conventions at www.xoc.net/standards/rvbanc.asp TheLeszynski Naming Conventions (LNC) and development style continue to be referenced in severalbooks and have been incorporated in various websites Because URLs frequently change, a search isprobably the best bet for finding a publication of the LNC

Appendix L: Naming Conventions

47033bapp12v6.5.qxd 3/30/07 12:39 AM Page 1028

Trang 37

So much for the history The critical part is to recognize that the Hungarian notation is pretty much versally recognized, if not adopted, and that it continues to be adapted to keep up with technology.Some tags are becoming obsolete and new ones are continuously added Although some tags may beretired, there are still programs using them, so it is handy to know where to find a translator, which, inthis case, is a table of tag definitions.

uni-The Fundamentals of the Hungarian Convention

The Hungarian convention has a very straightforward design It dictates that a name may contain up tofive parts, and that the parts are combined in the order of prefix(es), tag, base name, qualifier, and suffix:

A prefix precedes a tag to provide clarification It can describe one or more important properties

with one or two lowercase characters

A tag is considered by some to be the critical, non-optional element A tag should be unique and

easily differentiated from similarly named tags A tag is typically three (occasionally four) ercase characters that identify what the object is — a table, form, or text box, for example Thetag is usually a mnemonic abbreviation, such as tbl, frm, and txtor the first letter of eachword from multiword items Exceptions are often due to the tag already being assigned for adifferent purpose, adopting a tag from another program, and, of course, that it isn’t always easy

low-to create an intuitive three-letter abbreviation

The base name is a descriptive name that defines the particular object This could be the layman’s

term used to concisely identify the subject Use proper case and be brief but clear

A qualifier is an extension that indicates how the object is being used Qualifiers should be title

case and as short as practical, without sacrificing comprehension For example, the qualifier Avgmay be added to a query name to indicate that the query calculated the qryStudentGradeAvg(or qsumStudentGradeAvg)

A suffix is rarely needed Its purpose is to differentiate object names that could otherwise be

identical The suffix is written in title case or as a number and should be as short as practical.For example, a series of queries that calculate the average grade for each grade (see the need tomake a distinction?) could be named qryStudentGradeAvg4, qryStudentGradeAvg5, andqryStudentGradeAvg6, indicating the average for the fourth grade, the fifth grade, and thesixth grade class, respectively And, although many developers avoid using the underscore,some developers like to separate the suffix by using one, as in qryStudentGradeAvg_4.Although it isn’t necessary for an object name to contain all of the parts, nearly every name will contain

a tag and a base name For example, here’s the name for a table: tblStudent You can quickly see that itconforms to the rules — there are no spaces, the tag is all lowercase, and the base name is title case That

is a fairly universally accepted format Remember, object names should never include special characters

or spaces Other guidelines that you may want to follow are covered in the “Rules for CreatingNames — Adding the Personal Touch” section later in this appendix

1029

Appendix L: Naming Conventions

47033bapp12v6.5.qxd 3/30/07 12:39 AM Page 1029

Trang 38

The flag is the optional sixth part to a name A flag affects where an object appears in lists and is effectivefor grouping items at the beginning or the end of a list The following table describes common flags.

not be seen by the end user, but not hidden

zt Indicates a temporary object that is created programmatically, such as a

query built by code, and not preserved after it has been run

zz Denotes an object that you are no longer using and that is waiting to be

deleted

Rules for Creating Names —

Adding the Per sonal Touch

Developers tend to have an independent streak, which often means that we like to do things our ownway Thankfully, development is a creative process so typically there are multiple ways to achieve thedesired results That’s also the case with naming conventions Even if you choose to adopt existing stan-dards, there are plenty of opportunities to incorporate your own preferences and come up with a systemthat is easy for you to remember, implement, and share But before you start customizing things, it’s still

a good idea to understand the basic rules and principles of naming conventions The following sectionsprovide information to help you to both work with existing standards and create your own You mayfind that a combination works best

Starting with the Basics

Naming conventions apply to application objects, such as forms, reports, controls, queries, and defined objects, as well as to Access database engine (ACE) (and Jet) objects such as containers, data-bases, fields, queryDefs, tableDefs, and workspaces

user-Consistency is the key As stated earlier, it’s best to determine your naming conventions before you ate the first object in your database so that you can apply them consistently throughout your application.Remember that even when following an established naming convention, there will be plenty of situa-tions that challenge your interpretation of how to apply it

cre-Remember that object names should never include special characters or spaces.

Appendix L: Naming Conventions

47033bapp12v6.5.qxd 3/30/07 12:39 AM Page 1030

Trang 39

Next, think KISS (Keep It Short and Simple) Although Access allows up to 64 characters for each objectname, no one wants to type or read names that are that long Plus, your application may need to inter-face with other programs that are more restrictive in name length (If your object names aren’t compati-ble with those programs, you could be in for a lot of extra work.) For example, prior to SQL Server 6.0,field names needed to be lowercase for upsizing from Access to the SQL Server Prior to SQL Server 7.0,field and table names were limited to 30 characters and required an underscore instead of allowing anembedded space As you can see, just because Access allows 64 characters doesn’t mean it is a goodthing to create 64-character names.

There have been situations with Access 2003 and WindowsXP where an excessively long path to a table name caused Access to close If you are using Windows XP and your database is in a folder in MyDocuments, for example, that automatically adds about 50 characters to the file path.

Periods do not belong in names Periods are a special character that can cause your code to break.The following are some basic rules and guidelines that apply to both the name and the elements ofobjects:

❑ Names can contain up to 64 characters (but shorter is better, as previously discussed)

❑ Use complete words in names If you absolutely must use an abbreviation, ensure that it’s astandard, easy-to-interpret one You might use FName and LName for FirstName andLastName, for example, or in a table with company details you might have field names ofCoName, CoAddress, and so on

❑ Names can consist of any combination of letters and numbers For example, in tables with tiple address lines, it’s common to see Address1 and Address2

mul-❑ Be aware: While spaces and special characters — except period (.), exclamation point (!), accentgrave (`), and brackets ([]) — are all technically acceptable, they are known to create problems

in table and field names Do not use them (We strongly advise you to remove the spaces andcharacters if you are going to customize and add code to work with these objects.)

❑ Don’t begin a name with a leading space (Just don’t use spaces If readability is an issue, usecase — capitalize the first letter of each word, like this: June07MarketingOutlook.)

❑ Do not include control characters ASCII values 0–31 (remember that special character thing) SeeAppendix K to learn about special characters

❑ Don’t duplicate the name of a property or other element used by DAO

❑ Avoid a series of uppercase letters — these are reserved for formal abbreviations, such as USA

❑ Names are typically singular rather than plural, for example LastNamefor a field or txtStatefor a text box

❑ Include the base name of the object(s) that it is built on, when practical and logical, such asEventCityfor the field City in the table tblEvent

If you change the name of an object, remember that the name also needs to be updated in any code, modules, or other objects that reference it.

1031

Appendix L: Naming Conventions

47033bapp12v6.5.qxd 3/30/07 12:39 AM Page 1031

Trang 40

❑ List multiple base objects left-to-right in descending order of importance, such as

tblStudentClassfor a table that joins records from tblStudentswith records fromtblClass

❑ A name should use title case construction for the base It is preceded by a lowercase, three-lettertag, such as in tblStudentClass, lblClassDate, or intLattePrice

Some Additional Thoughts About Other Objects

If you are going to customize existing conventions or create your own, there are several other things thatyou will want to consider The following are some of the more common objects that you’ll want to haverules for handling

Variables and Routines

The body of a variable or routine name should use mixed case and should be only long enough todescribe its purpose For example, Dim intFormCount As Integerreturns the number of open forms

Functions

Function names should begin with a verb, and it may add clarity to prefix them with an ffor fnc Thiscan make functions easier to locate and identify when you are perusing through code Avoid using fn_because that is the prefix that SQL Server uses for functions fDisplayUnexpectedError, for example,

is clearly a function and not the name of a field that contains captured error messages

Stored procedure names should begin with a verb Having a tag precede the base name facilitates

sort-ing —insfor insert and arcfor archive, for example When applying tags, avoid sp_, dt_, and xp_because, again, they are used by SQL Server fCloseAllFormsis a good example of a clear and

concise name

Constants

The base name of a constant is often UPPERCASE_WORDSwith underscores (_) between words Prefixessuch as i, s, g, and mcan be very useful in understanding the value and the scope of a constant Forexample, in the new line character string gsNEW_LINE, the gindicates that it is global to entire applica-tion and the sindicates that it’s a string

Constants should be prefixed by the scope prefixes mor gfor module or global, respectively A constant

is indicated by appending the letter cto the end of the data type, or it can have the generic tag con Forthe constant gintcDiscount, gis the scope, intindicates the data type, cmeans it’s a constant, and thebase name is Discount conDiscountnames the same constant, but conveys less information because ituses the generic tag mdblcPiindicates module level (m), double (dbl) constant (c) with the base name

Pi

Classes

A class defines a user-defined object Because this invents a new data type, you need to invent a new tagfor the object You can add a base name to the tag to spell out the abbreviation indicated by the tag.Chapter 13, for example, used the class module clsClassroom

Appendix L: Naming Conventions

47033bapp12v6.5.qxd 3/30/07 12:39 AM Page 1032

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

TỪ KHÓA LIÊN QUAN

w