Академический Документы
Профессиональный Документы
Культура Документы
Table of Contents
Worksheet Functions
Sample formulas to complete common worksheet tasks.
Conditional Formatting
Demonstrates how to change the formatting (I.e. font, cell color)
applied to a cell depending on the current value of the cell.
Data Validation
Shows how to set up restrictions for the values that can be entered
into a cell.
Chart Labeling
A macro to automate the labeling of an XY-Scatter chart.
Repeating Tasks
Sample looping macro code and an explanation of how to modify
recorded code to repeat tasks on a range of cells or a selected
range.
Microsoft provides examples of Visual Basic for Applications procedures for illustration only, without warranty either expressed or implied, including, but not
limited to the implied warranties of merchantability and/or fitness for a particular purpose. The Visual Basic procedures in this workbook are provided 'as is'
and Microsoft does not guarantee that they can be used in all situations. While Microsoft Technical Support Engineers can help explain the functionality of a
particular macro, they will not modify these examples to provide added functionality, nor will they help you construct macros to meet your specific needs. If
you have limited programming experience, you may want to consult one of the Microsoft Solution Providers.
able of Contents
Arrays
Macro code to demonstrate how to transfer array contents to a
worksheet.
Events
Examples to demonstrate how some events can trigger macro
code to run.
Automation
Sample macro code to demonstrate how Microsoft Excel can
automate other Microsoft Office applications.
s for illustration only, without warranty either expressed or implied, including, but not
particular purpose. The Visual Basic procedures in this workbook are provided 'as is'
. While Microsoft Technical Support Engineers can help explain the functionality of a
functionality, nor will they help you construct macros to meet your specific needs. If
may want to consult one of the Microsoft Solution Providers.
New Format
#DIV/0!
If the menu items are not present and for additional information on how to use or install the
Lookup Wizard, use the Office Assistant and perform a search using the phrase "Lookup Wizard".
Conditional Formatting
Conditional Formatting allows you to change the formatting applied
to cell depending on the current value of the cell. This can make
auditing large worksheets much faster by automatically highlighting
exceptions. Conditional Formatting allows you to apply up to three
separate conditions to a cell.
Conditional Formatting allows you to change the font style, borders,
and cell patterns.
Conditional Formatting Example #1
Cells H10:H14 contain three Conditional Formatting rules that will
change the formatting of the cells depending on the values entered
into the cells.
To see the conditions applied to the cells, select cell H10, and then
click Conditional Formatting on the Format menu.
4
7
text
1
15
2.5
4
#DIV/0!
5
#DIV/0!
10
20
30
40
50
4
5
8
Data Validation
Data Validation allows you to set up restrictions for the values that
can be entered into a cell. The following examples present several
common scenarios for using Data Validation.
Data Validation Example #1 - Restricting Entry to Numeric Values
Cells H9:H13 have been formatted with a validation rule that
restricts cell entries to numeric values. This example utilizes the
Stop style for the Error alert, which prevents you from making an
invalid entry into the selected cell.
To see the Validation settings for this example, select cell H9, and
then click Validation on the Data menu.
Data Validation Example #2 - Restricting the Length of a Text Entry
Cells H19:H23 have been formatted with a validation rule that
restricts the length of text entries to seven characters or less. This
example utilizes the Warning style for the Error alert, which gives
you the option to cancel the current entry, or enter the invalid value
into the selected cell.
To see the Validation settings for this example, select cell H19, and
then click Validation on the Data menu.
Data Validation Example #3 - Restricting Entry to a Range of Whole Numbers
Cells H30:H34 have been formatted with a validation rule that will
alert you if you do not enter a whole number between 1 and 10.
This example utilizes the Information style for the Error alert, which
informs you of an invalid entry, but allows you to keep the current
value.
To see the Validation settings for this example, select cell H30, and
then click Validation on the Data menu.
Data Validation Example #4 - Restricting Cell Entry to a List of Values
Cells H41:H45 have been formatted with a validation rule that
restricts the entries to a list of values. The list of valid entries is
contained in cells M41:M49. When you select a cell within the
range H41:H45, a dropdown arrow appears on the cell. When you
click the arrow, the list of valid entries is displayed. You can simply
click the entry that you wish to make. This example utilizes the
Stop style for the Error alert, which prevents you from making an
invalid entry in the cell.
To see the Validation settings for this example, select cell H41, and
then click Validation on the Data menu.
Bob
Chris
David
John
Mike
Perry
Randal
Steve
Tim
Place
Place Labels
Labels on
on
Chart
Chart
Reset
Reset Chart
Chart
View
View Code
Y Values
9
8
7
6
5
YV
4
3
2
1
0
1
10
View
View Code
Code
Y Values
10
Repeating Tasks
Often it is necessary to perform the same task on a group of items. These items may be cells in a
range, worksheets in a workbook or workbooks in the application. Although the macro recorder
cannot record loops, the recorder can still be used to record the main task to be repeated. Then,
with some minor modifications to the recorded code, various types of loops can be created
depending on what is needed for an individual project.
The samples below focus on a scenario where the programmer has a range of cells in column A
containing numbers, and depending on the value of the cell, wishes to change the color of the
corresponding cell in column B.
First, we can record the single step process of changing the color of the background of a cell:
To record: From the Tools menu, click Macro, then click Record New Macro. While recording,
from the Format menu, click Cells. Then, click the Patterns tab and select a color.
This sample uses yellow (.ColorIndex=6). Now stop the recorder using the Stop button on the Stop
Recording toolbar. The currently selected cell will change color and the following macro will have
been recorded:
Sub Recorded_Macro()
'
' Macro recorded 11/18/98
'
With Selection.Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub
Goto
Goto Recorded_Macro
Recorded_Macro
Sample
Sample Code
Code
Note: If, while recording, you selected a cell, your macro may contain something similar to
Range("A3").Select. You may want to remove this line, since every time the macro is run,
this line will force the cell specified in the Range object to be selected. If you want that cell to be
selected first then leave that line in the macro.
Now, we can modify the code slightly and add one of the various looping structures to the recorded
code.
Sub For_Each_Next_Sample()
'
' Macro recorded 11/18/98
'
For Each cell_in_loop In Range("A1:A5")
If cell_in_loop.Value > 20 Then
With cell_in_loop.Offset(0, 1).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End If
Next
End Sub
Goto
Goto For_Each_Next
For_Each_Next
Sample
Sample Code
Code
ForNext Loop
If you know how many times you wish to loop through your code you can use a For...Next loop.
Using our example, if you want to only check ten cells down, starting from the selected cell, then
your modified recorded code might look like this:
Sub For_Next_Sample()
Goto
For..Next
Goto For_Next
For..Next Sample
Sample
Code
Code
For Counter = 0 To 9
If Selection.Offset(Counter, 0).Value > 20 Then
With Selection.Offset(Counter, 1).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End If
Next
End Sub
Here the Selection object is being used so that the code is not specific to any given range, but will
always loop through ten (0 to 9 as a counter) cells below the active cell. The Counter variable
increments each time through the loop and can be used within the looping structure. Here it is used
as an Offset argument to indicate how many rows to offset from Selection (the current cell). So, if
we start this macro and the active cell is A1, the first time through the loop the Counter variable will
equal 0, therefore we will Offset 0 rows from A1 as shown in the Selection.Offset(Counter, 0).Value
statement.
DoLoop
To determine whether or not to stop a loop based on a certain condition, a DoLoop might be
appropriate. This looping structure allows you to check properties or variable conditions before the
loop is executed. In the sample below, we continue to loop until the referenced cell's row
number, Selection.Offset(Counter, 0).Row, has exceeded 100. This can be useful if you
never want to perform the looping task below row 100.
Sub Do_Loop_Sample()
Goto
Goto Do_Loop
Do_Loop Sample
Sample
Code
Code
Counter = 0
Do Until Selection.Offset(Counter, 0).Row > 100
If Selection.Offset(Counter, 0).Value > 20 Then
With Selection.Offset(Counter, 1).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End If
Counter = Counter + 1
Loop
End Sub
Note: There are three more types of DoLoops available. The various forms offer more flexibility
when needed in various circumstances.
To find more information about these, and more detail about the other looping structures, please
access Help from within the Visual Basic Environment and use the keyword looping.
Sub ArrayDump1()
'For a one-dimensional horizontal array
Dim x(1 To 10) As Double 'Declares an array of size 10
For j = 1 To 10
'Calculates sample values
x(j) = j * j
Next j
'Transfers array contents to a horizontal area
Range(Cells(2, 1), Cells(2, 10)).FormulaArray = x
End Sub
Goto
Goto ArrayDump1
ArrayDump1
Sample
Sample Code
Code
The above example works correctly when the destination worksheet cells involve only one row.
However, when the contents of an array need to be transferred to a range of cells with a vertical,
as opposed to a horizontal orientation (that is, one column by several rows), the above example is
no longer valid.
Within a two-dimensional array you must change the orientation of the array. To do this, you can
declare the array a two-dimensional array with dimensions of several rows by one column. For
example:
Sub arraydump2()
'For a two-dimensional vertical array
'Declares an array ten rows by one column
Dim x(1 To 10, 1 To 1) As Double
'Calculates random values
For j = 1 To 10
x(j, 1) = j * j
Next j
'Transfers array contents to a vertical area
Range(Cells(1, 2), Cells(10, 2)).FormulaArray = x
End Sub
The two-dimensional array shown in this example allows Visual Basic to set the orientation of the
array as vertical; therefore, the array can be transferred to a worksheet without a loop.
Goto
Goto ArrayDump2
ArrayDump2
Sample
Sample Code
Code
Goto
Goto ArrayDump1
ArrayDump1
Sample
Sample Code
Code
Goto
Goto ArrayDump2
ArrayDump2
Sample Code
API Examples
An API (Application Programming Interface) is a function contained in DLL file.
These functions are normally used by windows and other applications but they can also be used by the end user.
Note: Exercise care when experimenting with API calls. Save your work often to avoid any problems.
Because they were designed to be called by the system and by applications, most error trapping has not been implemented.
This means that you may cause system hangs, crashes or other unintended side effects when experimenting with API calls.
The following examples show how to use some of the basic APIs. These have been tested under Windows98 and Excel 2000.
There are multiple ways to use these functions and it is up to the programmer to determine which is best for the result they are
Option Explicit
Private Declare Function GetLogicalDriveStrings Lib "kernel32" Alias "GetLogicalDriveStringsA
(ByVal nBufferLength As Long, _
ByVal lpBuffer As String) As Long
Sub Get_Logical_Drive_String()
Dim DrvString As String
Dim TotDrvs As Long
Dim Counter As Integer
Goto
Goto Get_Logical_Drive_String
Get_Logical_Drive_String
Sample
Sample Code
Code
Sub Get_System_Metrics()
Goto
Dim XVal As Long, YVal As Long
Goto Get_System_Metrics
Get_System_Metrics
Sample Code
YVal = GetSystemMetrics(SM_CYSCREEN)
XVal = GetSystemMetrics(SM_CXSCREEN)
MsgBox "Your Screen Resolution is " & XVal & " by " & YVal
End Sub
Return the short path name of a long path and file name
The following function takes a Long File Name and returns the Short File name
displaying both in a message box.
Private Declare Function GetShortPathName Lib "KERNEL32.DLL" Alias "GetShortPathNameA" _
(ByVal lpctstrLongName As String, _
ByVal lptstrShortName As String, _
ByVal bufLen As Long) As Long
Sub Get_Short_Name()
Dim LongStr As String, ShortStr As String
Dim lStrLen As Long, lRet As Long
Goto
Goto Get_Short_Name
Get_Short_Name
Sample
Sample Code
Code
Goto
Goto Get_Short_Name
Get_Short_Name
Sample
Sample Code
Code
'LongStr is any long file name or variable pointing to a file
LongStr = ThisWorkbook.FullName
lRet = GetShortPathName(LongStr, ShortStr, lStrLen)
'This allows us to create a buffer the same length as
'the returned string, saving us the trouble of having
'to strip the left of the buffer to get the string
ShortStr = String(lRet, " ")
lRet = GetShortPathName(LongStr, ShortStr, lRet)
MsgBox LongStr & "
was converted to
" & ShortStr
End Sub
Option Explicit
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuf
nSize As Long) As Long
Sub Get_Computer_Name()
Goto
Goto Get_Computer_Name
Get_Computer_Name
Dim Comp_Name_B As String * 255
Sample Code
Dim Comp_Name As String
GetComputerName Comp_Name_B, Len(Comp_Name_B)
'but the string is always ended with a null terminated string so we can use the Chr(0) fu
Comp_Name = Left(Comp_Name_B, InStr(Comp_Name_B, Chr(0)))
'and return only the computer name
MsgBox Comp_Name
End Sub
Option Explicit
Private Declare Function GetDiskFreeSpace Lib "KERNEL32.DLL" Alias "GetDiskFreeSpaceA" (ByVal
dwSectors As Long, _
dwBytes As Long, _
dwFreeClusters As Long, _
dwTotalClusters As Long) As Long
Sub Get_Disk_Free_Space()
Dim f As Long, iSectors As Long
Goto
Goto Get_Disk_Free_Space
Get_Disk_Free_Space
Dim iTotal As Long, rTotal As Long
Sample Code
Dim iFree As Long, rFree As Long
Dim iBytes As Long
Dim sName As String, s As String
sName = "C:\"
Option Explicit
Declare Function GetSystemDirectory Lib "kernel32" Alias "GetSystemDirectoryA" (ByVal lpBuffe
ByVal nSize As Long) As Long
Sub Get_System_Directory()
Dim Sys_Dir As String, Res As Long
Res = GetSystemDirectory(Sys_Dir, 0&)
Sys_Dir = String(Res - 1, " ")
Res = GetSystemDirectory(Sys_Dir, Res)
MsgBox Sys_Dir
End Sub
Goto
Goto GetSystemDirectory
Sample
Sample Code
Code
Goto
Goto Num_Devs
Num_Devs
Sample
Sample Code
Code
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As St
ByVal lpWindowName As String) As Long
Private Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long, _
ByVal hWndInsertAfter As Long, _
ByVal x As Long, _
Goto
Goto SetOnTop
SetOnTop
ByVal y As Long, _
Sample
Sample Code
Code
ByVal cx As Long, _
ByVal cy As Long, _
ByVal wFlags As Long) As Long
Global Const HWND_TOPMOST = -1
Global Const HWND_NOTOPMOST = -2
Sub SetOnTop()
Dim WinHnd As Long, SUCCESS As Long
WinHnd = FindWindow("xlmain", Application.Caption)
SUCCESS = SetWindowPos(WinHnd, HWND_TOPMOST, 0, 0, 0, 0, Flags)
'The following line is here just to switch Excel back to normal operation
'after 20 seconds
Application.OnTime Now + TimeValue("00:00:20"), "NotOnTop"
End Sub
Sub NotOnTop()
Dim WinHnd As Long, SUCCESS As Long
WinHnd = FindWindow("xlmain", Application.Caption)
SUCCESS = SetWindowPos(WinHnd, HWND_NOTOPMOST, 0, 0, 0, 0, Flags)
End Sub
As String, _
oot As String, _
String, _
BeforeDoubleClick
A very popular type of Event is the BeforeDoubleClick event on a worksheet. A very simple example may look
like:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As
Boolean)
MsgBox "You double clicked on cell " & Target.Address
Cancel = True
End Sub
This event will fire whenever the user double-clicks a cell in the worksheet. The parameter Target is passed into
the macro so the programmer will know what cell has been double clicked. The Cancel argument has a default
value of False but can be changed to True within the code. Setting Cancel to True will cancel the default action
for the event. In this case, the default action for a double click on a cell is to switch to edit mode on the cell.
Since we set Cancel to True, this will not occur. If you want to still have the default action occur, then the
Cancel=True line can be removed.
Change
Another very useful event is the Change event for a worksheet. Any time the user enters a new value in any cell
this event fires.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
MsgBox "This sheet has changed in cell " & Target.Address
End Sub
Note: This event does not occur if the sheet has just been recalculated. There is an event called Calculate
which will fire when the worksheet recalculates.
BeforeClose
A useful Workbook related event is BeforeClose. These events can be used to perform "housekeeping" tasks
before a file is saved or closed.
Sub Workbook_BeforeClose(Cancel As Boolean)
a = MsgBox("Do you really want to close the workbook?", vbYesNo)
If a = vbNo Then Cancel = True
End Sub
In this example, the user is prompted to close the file regardless if the file has been saved or not.
Automation
Automation is a feature of the Component Object Model (COM), a technology that applications use to expose their
objects to development tools, macro languages, and other applications that support Automation. For example, a
spreadsheet application may expose a worksheet, chart, cell, or range of cells each as a different type of object. A
word processor might expose objects such as an application, a document, a paragraph, a sentence, a bookmark, or
a selection. The following examples demonstrate automating tasks between Microsoft Excel and other Microsoft
applications.
For more information on Automation, refer to Understanding Automation in VBA Help.
MICROSOFT ACCESS
This example returns the location of the Microsoft Access sample databases.
Sub MS_Access()
Dim AccDir As String
Dim acc As Object
'OLE automation to Access
Set acc = CreateObject("access.application")
'Return the path for msaccess.exe
AccDir = acc.SysCmd(Action:=acSysCmdAccessDir)
'Display the path
MsgBox "MSAccess.exe is located in " & AccDir
'Free up variable storage space
Set acc = Nothing
End Sub
Goto
Goto MS_Access
MS_Access
Automation
Automation Code
Code
MICROSOFT WORD
This example copies the chart from the Chart Labels sheet into a new Microsoft Word document.
Sub MS_Word()
Dim wd As Object
'Create a Microsoft Word session
Set wd = CreateObject("word.application")
Goto
'Copy the chart on the Chart Labels sheet
Goto MS_Word
Automation
Code
Automation
Worksheets("Chart Labeling").ChartObjects(1).Chart.ChartArea.Copy
'Make document visible
wd.Visible = True
'Activate MS Word
AppActivate wd.Name
With wd
'Create a new document in Microsoft Word
.Documents.Add
'Insert a paragraph
.Selection.TypeParagraph
'Paste the chart
.Selection.PasteSpecial link:=True, DisplayAsIcon:=False, Placement:=wdInLine
End With
Set wd = Nothing
End Sub
MICROSOFT POWERPOINT
This example copies the chart from the Chart Labels sheet into a new Microsoft PowerPoint presentation.
Sub MS_PowerPoint()
Dim ppt As Object, pres As Object
'Create a Microsoft PowerPoint session
Set ppt = CreateObject("powerpoint.application")
'Copy the chart on the Chart Labels Demo sheet
Worksheets("Chart Labeling").ChartObjects(1).Copy
'Create a new document in Microsoft PowerPoint
Set pres = ppt.Presentations.Add
'Add a slide
pres.Slides.Add 1, ppLayoutBlank
'Make PowerPoint visible
ppt.Visible = True
'Activate PowerPoint
AppActivate ppt.Name
'Paste the chart
ppt.ActiveWindow.View.Paste
Set ppt = Nothing
End Sub
Goto
Goto MS_Powerpoint
MS_Powerpoint
Automation
Automation Code
Code
MICROSOFT OUTLOOK
This example creates and adds information to a new Outlook task. Run Outlook and click Tasks on the Outlook bar
to see the new task.
NOTE: It may take a few minutes for the task to appear.
Sub MS_Outlook()
Goto
Goto MS_Outlook
MS_Outlook
Dim ol As Object, myItem As Object
Automation
Automation Code
Code
'Create a Microsoft Outlook session
Set ol = CreateObject("outlook.application")
'Create a task
Set myItem = ol.CreateItem(olTaskItem)
'Add information to the new task
With myItem
.Subject = "New VBA task"
.Body = "This task was created via Automation from Microsoft Excel"
.NoAging = True
.Close (olSave)
End With
'Remove object from memory
Set ol = Nothing
End Sub
S_Access
S_Access
ion Code
tion
Code
S_Word
S_Word
on Code
owerpoint
owerpoint
on Code
Code
Sub RetrieveISAMdata()
''' NOTE: This subroutine requires that you reference the
''
latest version of the following library:
'''
''
Microsoft ActiveX Data Objects Library
Dim
Dim
Dim
Dim
Dim
Goto
Goto Retrieve
Retrieve ISAM
ISAM
Data
Data Example
Example Sample
Sample
Code
Code
conn As ADODB.Connection
rst As ADODB.Recordset
NewBook As Workbook
PathToDatabase As String
i As Integer
conn As ADODB.Connection
rst As ADODB.Recordset
Nsql As String, Njoin As String, Ncriteria As String
NewBook As Workbook
i As Integer
Goto
Goto Retrieve
Retrieve Access
Access
Data
Data Example
Example Sample
Sample
Code
Code
Goto
Goto List
List Tables
Tables
Example Sample Code
End With
Set rst = conn.OpenSchema(adSchemaTables)
While Not rst.EOF
If rst.Fields("TABLE_TYPE") <> "VIEW" Then
MsgBox rst.Fields("TABLE_NAME")
End If
rst.MoveNext
Wend
Set rst = Nothing
conn.Close
End Sub
List Fields in a Table
This example lists the fileds in the Customer.dbf dBase file. For this
example, you must have the Microsoft dBase driver installed. You must also
have the Customer.dbf file installed.
Sub ListFields()
''' NOTE: This subroutine requires that you reference the
''
latest version of the following library:
'''
''
Microsoft ActiveX Data Objects Library
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim fld As ADODB.Field
' Create the Connection object.
Set conn = New ADODB.Connection
With conn
' Set the OleDB provider for the connection.
.Provider = "Microsoft.JET.OLEDB.4.0"
' Open a connection to Northwind.mdb.
.Open Application.Path & "\samples\northwind.mdb"
End With
Set rst = New ADODB.Recordset
With rst
.ActiveConnection = conn
.Open "SELECT * FROM customers"
End With
For Each fld In rst.Fields
MsgBox fld.Name
Goto
Goto List Fields
Example
Example Sample Code
Next fld
Set rst = Nothing
conn.Close
End Sub
Add Data to a New Table in an Access Database
This example adds a new table to the Northwind.mdb database. The
subroutine then populates the table with data located in cells S1:V30 of this
worksheet. This example requires that the Northwind.mdb file is installed on
your computer.
Sub CreateTable()
''' NOTE: This subroutine requires that you reference the
''
latest version of the following library:
'''
''
Microsoft ActiveX Data Objects Library
'''
Microsoft ADO Ext. 2.1 for DDL and Security
' The first four Dim lines are simultaneously declaring and
' creating new objects. You can use this syntax, or you can
' use the Set statement to create the objects.
Dim cat As New ADOX.Catalog
Dim tbl As New ADOX.Table
Dim conn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim looprange As Range
Dim currcell As Range
With conn
' Set the OleDB provider for the connection.
.Provider = "Microsoft.JET.OLEDB.4.0"
' Open a connection to Northwind.mdb.
.Open Application.Path & "\samples\northwind.mdb"
End With
' Set the active connection for the Catalog object.
cat.ActiveConnection = conn
With tbl
' Name the new table.
.Name = "SalesTable"
' Name the columns for the new table.
With .Columns
.Append "Name"
.Append "Region"
Goto
Goto Create
Create Table
Table
Example
Example Sample
Sample Code
Code
.Append "Product"
' The Sales column must be the Currency data type.
.Append "Sales", adCurrency
End With
End With
' Add the table to the database.
cat.Tables.Append tbl
With rst
.ActiveConnection = conn
' Open the new table. The LockType argument of the
' Open method must be set to adLockOptimistic in order
' add records to the table.
.Open "SalesTable", LockType:=adLockOptimistic
End With
' Set the range that contains the records to add to the database.
Set looprange = Range("s2", Range("s2").End(xlDown))
' Loop through the information on the worksheet.
For Each currcell In looprange
With rst
' Add a new record.
.AddNew
' Add information to the correct fields.
.Fields("Name").Value = currcell.Value
.Fields("Region").Value = currcell.Offset(0, 1).Value
.Fields("Product").Value = currcell.Offset(0, 2).Value
.Fields("Sales").Value = currcell.Offset(0, 3).Value
' Write the new record to the database.
.Update
End With
Next currcell
rst.Close
Set tbl = Nothing
Set cat = Nothing
conn.Close
End Sub
Trapping ADO Errors
This example illustrates how to trap, then return relevant information about
an error that you may receive when running ADO code.
Sub Trap_ADO_Errors()
Goto
Goto Trap
Trap ADO
ADO Errors
Errors
Example
Example Sample
Sample Code
Code
Goto
Goto Retrieve
Retrieve ISAM
ISAM
Data
Data Example
Example Sample
Sample
Code
Code
Please Do Not
Modify this table.
It is necessary for
examples contained
in this workbook.
Name
Tom
Tom
Tom
Tom
Mike
Mike
Mike
Mike
Lindy
Lindy
Lindy
Lindy
Jan
Jan
Jan
Jan
Harvey
Harvey
Harvey
Harvey
Greg
Greg
Greg
Greg
Andy
Andy
Andy
Andy
Goto
Goto Retrieve
Retrieve Access
Access
Data
Data Example
Example Sample
Code
Code
nitsInStock)>20));"
Goto
Goto List
List Tables
Tables
Example
Example Sample
Sample Code
Code
Goto
Goto List
List Fields
Fields
Example
Example Sample
Sample Code
Code
Goto
Goto Create
Create Table
Table
Example
Example Sample
Sample Code
Code
Goto
Goto Trap
Trap ADO
ADO Errors
Errors
Example
Example Sample
Sample Code
Region
East
East
East
East
South
South
South
South
South
South
South
South
East
East
East
East
South
South
South
South
North
North
North
North
North
North
North
North
Product
Apples
Bananas
Pears
Oranges
Bananas
Oranges
Apples
Pears
Apples
Pears
Oranges
Bananas
Bananas
Apples
Pears
Oranges
Oranges
Bananas
Apples
Pears
Pears
Oranges
Bananas
Apples
Pears
Oranges
Bananas
Apples
Sales
$759
$707
$188
$121
$689
$345
$244
$962
$732
$908
$755
$30
$979
$123
$21
$799
$244
$516
$562
$190
$300
$704
$785
$527
$513
$800
$138
$430