Tải bản đầy đủ (.pdf) (95 trang)

Excel 2002 Power Programming with VBA phần 10 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (663.91 KB, 95 trang )

852
Part VII ✦ Other Topics
using a UserForm_QueryClose event procedure in the code module for the
UserForm. The following example does not allow the user to close the form by click-
ing the Close button:
Private Sub UserForm_QueryClose _
(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
MsgBox “You can’t close the form like that.”
Cancel = True
End If
End Sub
I’ve created a UserForm whose controls are linked to cells
on the worksheet with the ControlSource property.
Is this the best way to do this?
In general, you should avoid using links to worksheet cells unless you absolutely
must. Doing so can slow your application down because the worksheet is recalcu-
lated every time a control changes the cell.
Is there any way to create a control array for a UserForm? It’s possible
with Visual Basic 6.0, but I can’t figure out how to do it with Excel VBA.
You can’t create a control array, but you can create an array of Control objects.
The following code creates an array consisting of all CommandButton controls:
Private Sub UserForm_Initialize()
Dim Buttons() As CommandButton
Cnt = 0
For Each Ctl In UserForm1.Controls
If TypeName(Ctl) = “CommandButton” Then
Cnt = Cnt + 1
ReDim Preserve Buttons(1 To Cnt)
Set Buttons(Cnt) = Ctl
End If


Next Ctl
End Sub
Is there any difference between hiding a UserForm
and unloading a UserForm?
Yes, the Hide method keeps the UserForm in memory but makes it invisible. The
Unload statement unloads the UserForm, beginning the “termination” process
(invoking the
Terminate event for the UserForm) and removing the UserForm from
memory.
4799-2 ch30.F 6/11/01 9:49 AM Page 852
853
Chapter 30 ✦ Frequently Asked Questions about Excel Programming
How can I make my UserForm stay open while I do other things?
By default, each UserForm is modal, which means that it must be dismissed before
you can do anything else. Beginning with Excel 2000, however, you can make a
UserForm modeless by writing
vbModeless as the argument for the Show method.
Here’s an example:
UserForm1.Show vbModeless
Excel 97 gives me a compile error when I write UserForm1.Show
vbModeless. How can I make the form modeless in Excel 2002,
while allowing it to remain modal in Excel 97?
Test for the version of Excel that the user is running and then execute a separate
procedure if the version is Excel 2000 or later. The following code demonstrates
how:
Sub ShowUserForm()
If Val(Application.Version) >= 9 Then
ShowModelessForm
Else
UserForm1.Show

End If
End Sub
Sub ShowModelessForm()
Dim frm As Object
Set frm = UserForm1
frm.Show 0 ‘ vbModeless
End Sub
Because the ShowModelessForm procedure is not executed in Excel 97, it will not
cause a compile error.
I need to display a progress indicator like those you see when you’re
installing software while a lengthy process is being executed.
How can I do this?
You can do this with a UserForm. Chapter 15 describes several different techniques,
including one where I gradually stretch a shape inside a frame while the lengthy
process is running.
4799-2 ch30.F 6/11/01 9:49 AM Page 853
854
Part VII ✦ Other Topics
How can I use Excel’s drawing tools to create
simple drawings on my UserForm?
You can’t use the drawing tools directly with a UserForm, but you can do so indi-
rectly. Start by creating the drawing on a worksheet. Then select the drawing and
choose Edit ➪ Copy. Activate your UserForm and insert an
Image object. Press F4 to
display the Properties window. Select the
Picture property and press Ctrl+V to
paste the clipboard contents to the Image control. You may also need to set the
AutoSize property to True.
How can I generate a list of files and directories into my UserForm so
the user can select a file from the list?

There’s no need to do that. Use VBA’s GetOpenFilename method. This displays a
“file open” dialog box in which the user can select a drive, directory, and file.
I have several 1-2-3 for Windows files and Quattro Pro for Windows
files that contain custom dialog boxes. Is there a utility to convert
these to Excel dialog boxes?
No.
I need to concatenate strings and display them in a ListBox control.
But when I do so, they aren’t aligned properly. How can I get them
to display equal spacing between strings?
You can use a monospaced font such as Courier New for the ListBox. A better
approach, however, is to set up your ListBox to use two columns (see Chapter 14
for details).
Is it possible to display a built-in Excel dialog box from VBA?
Most, but not all, of Excel’s dialog boxes can be displayed by using the
Application.Dialogs method. For example, the following instruction displays the
dialog box that enables you to format numbers in cells:
Application.Dialogs(xlDialogFormatNumber).Show
Use the Object Browser to display a list of the constants for the built-in dialog
boxes. Press F2 from the VBE, select the
Excel library, and search for xlDialog.
You’ll probably need to use some trial and error to locate the constant that corre-
sponds to the dialog you want to display.
4799-2 ch30.F 6/11/01 9:49 AM Page 854

856
Part VII ✦ Other Topics
Is it possible to create a UserForm box that lets the user
select a range in a worksheet by pointing?
Yes. Use the RefEdit control for this. See Chapter 14 for an example.
Is there a way to change the start-up position of a UserForm?

Yes, you can set the UserForm’s Left and Top properties. But for these to be effec-
tive, you need to set the UserForm’s
StartUpPosition property to 0.
Can I add an Excel 5/95 dialog sheet to my workbook?
Yes. Right-click any sheet tab in a workbook, and select Insert from the shortcut
menu. In the Insert dialog box, select MS Excel 5.0 Dialog. Be aware that none of the
information in this book applies to Excel 5/95 dialog sheets.
Add-Ins
Where can I get Excel add-ins?
You can get Excel add-ins from a number of places:
✦ Excel includes several add-ins you can use whenever you need them.
✦ You can download more add-ins from Microsoft’s Office Update Web site.
✦ Third-party developers distribute and sell add-ins for special purposes.
✦ Many developers create free add-ins and distribute them via their Internet
sites.
✦ You can create your own add-ins.
How do I install an add-in?
You can load an add-in by selecting either the Tools➪ Add-Ins command or the
File ➪ Open command. Using Tools➪ Add-Ins is the preferred method. An add-in
opened with File ➪ Open cannot be closed without using VBA.
When I install my add-in using Excel’s Add-Ins dialog box, it shows up
without a name or description. How can I give my add-in a description?
Before creating the add-in, use the File ➪ Properties command to bring up the
Properties dialog box. Click the Summary tab. In the Title box, enter the text that
you want to appear in the Add-Ins dialog box. In the Comments field, enter the
description for the add-in. Then create the add-in as usual.
4799-2 ch30.F 6/11/01 9:49 AM Page 856
857
Chapter 30 ✦ Frequently Asked Questions about Excel Programming
I have several add-ins that I no longer use, yet I can’t figure out how to

remove them from the Add-Ins Available list in the Add-Ins dialog box.
What’s the story?
Oddly, there is no way to remove unwanted add-ins from the list directly from Excel.
You must edit the Windows Registry and remove the references to the add-in files
you don’t want listed. Another way to do this is to move or delete the add-in files.
Then when you attempt to open the add-in from the Add-Ins dialog box, Excel will
ask if you want to remove the add-in from the list.
How do I create an add-in?
Activate any worksheet, and select File ➪ Save As. Then select Microsoft Excel Add-
in (*.xla) from the Save as type drop-down list.
I try to create an add-in, but the Save as type drop-down box doesn’t
provide Add-in as an option.
The most likely reason is that the active sheet is not a worksheet.
Should I convert all my essential workbooks to add-ins?
No! Although you can create an add-in from any workbook, not all workbooks are
suitable. When a workbook is converted to an add-in, it is essentially invisible. For
most workbooks, being invisible isn’t a good thing.
Is it necessary to keep two copies of my workbook,
the XLS version and the XLA version?
With versions prior to Excel 97, maintaining an XLS and an XLA version was neces-
sary. Beginning with Excel 97, however, this is no longer necessary. An add-in can
be converted back to a normal workbook.
How do I modify an add-in after it’s been created?
Activate the VBE (Alt+F11), and set the IsAddIn property of the ThisWorkbook
object to False. Make your changes, set the IsAddIn property to True, and resave
the file.
What’s the difference between an XLS file and an XLA file created from
an XLS file? Is the XLA version compiled? Does it run faster?
There isn’t a great deal of difference between the files, and you generally won’t
notice any speed differences. VBA code is always “compiled” before it is executed.

This is true whether it’s in an XLS file or an XLA file. However, XLA files contain the
actual VBA code, not compiled code.
4799-2 ch30.F 6/11/01 9:49 AM Page 857
858
Part VII ✦ Other Topics
How do I protect the code in my add-in from being viewed by others?
Activate the VBE and select Tools➪ xxxx Properties (where xxxx is the name of
your project). Click the Protection tab, select Lock project for viewing, and enter a
password.
Are my XLA add-ins safe? In other words, if I distribute an XLA file, can
I be assured that no one else will be able to view my code?
Protect your add-in by locking it with a password. This prevents most users from
being able to access your code. Recent versions of Excel have improved the secu-
rity features, but the password still may be broken by using any of a number of utili-
ties. Bottom line? Don’t think of an XLA as being a secure file.
CommandBars
I have a macro attached to a toolbar button. Is it possible to have the
macro perform a different action if the user presses Shift while the
button is clicked?
Yes, but you have to use a Windows API call to do it. Refer to Chapter 11 for details.
Excel 95 had a handy menu editor, but it’s missing in Excel 97
and later versions. What gives?
Beginning with Excel 97, the toolbars and menus in Excel are entirely different. Both
are called CommandBars. The menu editor is gone, but users can edit
CommandBars by using the Customize dialog box (select Tools➪ Customize).
Can I edit menus created by Excel 95’s menu editor?
Yes, but you’ll need to do so in Excel 95.
When I change a menu with the Customize dialog box, the menu is
changed permanently. How can I make the menu change apply to only
one workbook?

You’ll need to perform your menu changes with VBA code when the workbook is
opened, and restore the menu to normal when the workbook is closed.
I know you can use the FaceId property to add an image to a toolbar
control. But how do I figure out which FaceId value goes with a
particular image?
Microsoft didn’t provide any way to do this, but several utilities exist that make it
easy to identify the
FaceId values. See Chapter 22 for an add-in that you might find
helpful.
4799-2 ch30.F 6/11/01 9:49 AM Page 858
859
Chapter 30 ✦ Frequently Asked Questions about Excel Programming
I attached a new version of my toolbar to a workbook, but Excel
continues to use the older version. How do I get it to use the new
version of my toolbar?
When Excel opens a workbook that has an attached toolbar, it displays the toolbar
only if one with the same name does not already exist on the user’s system. The
best solution is to write VBA code to create the toolbar on the fly when the work-
book is opened and to delete it when the workbook is closed. Alternatively, you can
attach the toolbar to the workbook and then write code to delete the toolbar when
the workbook is closed.
I’ve made lots of changes to Excel’s toolbars. How can I restore all of
these toolbars to their original state?
You can use the Customize dialog box and reset each one manually. Or run the fol-
lowing procedure:
Sub ResetAllToolbars()
For Each tb In CommandBars
If tb.Type = msoBarTypeNormal Then
If tb.BuiltIn Then tb.Reset
End If

Next tb
End Sub
Be aware that this procedure will also remove any toolbar customizations per-
formed by add-ins.
How can I set things up so my custom menu is displayed only when a
particular workbook is active?
You need to make use of the WorkbookActivate and WorkbookDeactivate events.
In other words, write procedures in the code module for the
ThisWorkbook object
that hide the custom menu when the workbook is deactivated and unhide the cus-
tom menu when the workbook is activated.
How can I add a “spacer” between two buttons on a toolbar?
Set the BeginGroup property of the control after the spacer to True.
How do you display a check mark next to a menu item?
A check mark on a menu item is controlled by the menu item’s State property. The
following instruction, for example, displays a check mark next to the menu item
called My Item:
CommandBars(1).Commands(“MyMenu”). _
Commands(“My Item”).State = msoButtonDown
To uncheck the menu item, set the State property to msoButtonUp.
4799-2 ch30.F 6/11/01 9:49 AM Page 859
860
Part VII ✦ Other Topics
I accidentally deleted some items from the Worksheet menu and can’t
get them back. Restarting Excel doesn’t fix it.
Select Tools➪ Customize, and select the Toolbars tab in the Customize dialog box.
Select the Worksheet Menu Bar item, and click the Reset button.
How can I disable all the right-click shortcut menus?
The following procedure will do the job:
Sub DisableAllShortcutMenus()

Dim cb As CommandBar
For Each cb In CommandBars
If cb.Type = msoBarTypePopup Then _
cb.Enabled = False
Next cb
End Sub
Is there a way to disable the shortcut menus that appear when the
user clicks the right mouse button?
Yes, the following instruction will do the job:
CommandBars(“Toolbar List”).Enabled = False
I just entered CommandBars(“Toolbar List”).Enabled = False,
and it doesn’t work on my system!
The original version of Excel 97 had a problem with this instruction. It was cor-
rected in the SR-1 service release for Excel 97.
✦✦✦
4799-2 ch30.F 6/11/01 9:49 AM Page 860
Excel Resources
Online
I
f I’ve done my job, the information provided in this book
will be useful to you. It is, however, by no means compre-
hensive. In addition, new issues tend to crop up, so you’ll
want to make sure that you’re up to date. Therefore, I’ve com-
piled a list of additional resources that may help you become
more proficient in Excel application development. I’ve classi-
fied these resources into three categories:
✦ Microsoft technical support
✦ Internet newsgroups
✦ Internet Web sites
Microsoft Technical Support

Technical support is the common term for assistance pro-
vided by a software vendor. In this case, I’m talking about
assistance that comes directly from Microsoft. Microsoft’s
technical support is available in several different forms.
Support options
To find out your support options, choose the Help ➪ About
Microsoft Excel command. Then click the Tech Support but-
ton. This opens a help file that lists all the support options
offered by Microsoft, including both free and fee-based
support.
My experience is that you should use vendor standard tele-
phone support only as a last resort. Chances are, you’ll run up
a big phone bill (assuming that you can even get through) and
spend lots of time on hold, but you may or may not find an
answer to your question.
A
A
APPENDIX
✦✦✦✦
4799-2 AppA.F 6/11/01 9:49 AM Page 861
862
Appendixes
The truth is, the people who answer the phone are equipped to answer only the
most basic questions. And the answers to these basic questions are usually readily
available elsewhere.
Microsoft Knowledge Base
Your best bet for solving a problem may be the Microsoft Knowledge Base. This is
the primary Microsoft product information source —an extensive, searchable
database that consists of tens of thousands of detailed articles containing technical
information, bug lists, fix lists, and more.

You have free and unlimited access to the Knowledge Base via the Internet. The
URL is:

Microsoft Excel home page
The official home page of Excel is at:
/>Microsoft Office update
For product updates, add-ins, downloads, and other information about Office 2000
(including Excel), try this site:

Internet Newsgroups
Usenet is an Internet service that provides access to several thousand special inter-
est groups that enable you to communicate with people who share common inter-
ests. There are thousands of newsgroups covering virtually every topic you can
think of (and many that you haven’t). Typically, questions posed on a newsgroup
About the URLs Listed Here
As you know, the Internet is a dynamic entity that tends to change rapidly. Web sites are
often reorganized (especially those at the microsoft.com domain). Therefore, a particular
URL listed in this appendix may not be available when you try to access it. Each URL was
accurate at the time of this writing, but it’s possible that a URL may have changed by the
time you read this.
4799-2 AppA.F 6/11/01 9:49 AM Page 862
863
Appendix A ✦ Excel Resources Online
are answered within 24 hours — assuming, of course, that the questions are asked
in a manner that makes others want to reply.
Besides an Internet connection, you need special newsreader software to access
newsgroups. Microsoft Outlook Express (free) is a good choice. This product is
available on your Office 2002 CD-ROM. If you don’t have access to newsreader
software (or if your Internet connection doesn’t allow access to the newsgroups),
you can also access the microsoft.public.* newsgroups from this URL:

/>Spreadsheet newsgroups
The primary Usenet newsgroup for general spreadsheet users is:
comp.apps.spreadsheets
This newsgroup is intended for users of any spreadsheet brand, but about 90 per-
cent of the postings deal with Excel. My advice? Skip this one and head directly for
the Microsoft newsgroups.
Microsoft newsgroups
Microsoft has an extensive list of newsgroups, including quite a few devoted to
Excel. If your Internet service provider doesn’t carry the Microsoft newsgroups,
you can access them directly from Microsoft’s news server. You’ll need to configure
your newsreader software or Web browser to access Microsoft’s news server, which
is at this address:
msnews.microsoft.com
Table A-1 lists the key newsgroups you’ll find on Microsoft’s news server.
Table A-1
Microsoft.com’s Excel-Related Newsgroups
Newsgroup Topic
microsoft.public. Programming Excel with VBA or XLM macros
excel.programming
microsoft.public. Converting 1-2-3 or Quattro Pro sheets into Excel sheets
excel.123quattro
microsoft.public. Worksheet functions
excel.worksheet.functions
Continued
Note
4799-2 AppA.F 6/11/01 9:49 AM Page 863
864
Appendixes
Table A-1 (continued)
Newsgroup Topic

microsoft.public. Building charts with Excel
excel.charting
microsoft.public. Printing with Excel
excel.printing
microsoft.public. Using Microsoft Query and Data Access Objects (DAO)
excel.queryDAO in Excel
microsoft.public. Using the Data Map feature in Excel
excel.datamap
microsoft.public. Help with General Protection Faults or system failures
excel.crashesGPFs
microsoft.public. General topics that do not fit one of the other categories
excel.misc
microsoft.public. Using links in Excel
excel.links
microsoft.public. Excel issues on the Macintosh operating system
excel.macintosh
microsoft.public. OLE, DDE, and other cross-application issues
excel.interopoledde
microsoft.public. Setting up and installing Excel
excel.setup
microsoft.public. Spreadsheet Solutions templates and other XLT files
excel.templates
microsoft.public. Issues regarding the Excel Software Development Kit
excel.sdk
Searching newsgroups
Many people don’t realize that you can perform a keyword search on past news-
group postings. Often, this is an excellent alternative to posting a question to the
newsgroup because you can get the answer immediately. You can search the news-
groups at the following Web address:
/>Formerly, newsgroup searches were performed at the Deja.com Web site. That site

has closed down, and the newsgroup archives were purchased by Google.
Note
4799-2 AppA.F 6/11/01 9:49 AM Page 864
865
Appendix A ✦ Excel Resources Online
How does searching work? Assume you’re having a problem with the ListBox con-
trol on a UserForm. You can perform a search using the following keywords:
Excel,
ListBox, and UserForm. The Google search engine will probably find dozens of
newsgroup postings that deal with these topics. It may take a while to sift through
the messages, but there’s an excellent chance that you’ll find an answer to your
question.
Internet Web Sites
The Web has hundreds of sites that deal with Excel. I list a few of my favorites here.
Tips for Posting to a Newsgroup
1. Make sure that your question has not already been answered. Check the FAQ (if one
exists) and also perform a Google search (see “Searching newsgroups” in this
appendix).
2. Make the subject line descriptive. Postings with a subject line such as “Help me!”
and “Excel Question” are less likely to be answered than postings with a subject
such as “VBA Code to Resize a Chart in Excel 2002.”
3. Specify the spreadsheet product and version that you are using. In many cases, the
answer to your question depends on your version of Excel.
4. Make your question as specific as possible.
5. Keep your question brief and to the point, but provide enough information so it can
be adequately answered.
6. Indicate what you’ve done to try to answer your own question.
7. Post in the appropriate newsgroup, and don’t cross-post to other groups unless the
question applies to multiple groups.
8. Don’t type in all uppercase or all lowercase, and check your grammar and spelling.

9. Don’t include a file attachment.
10. Do not post in HTML format.
11. If you would like an e-mail reply, don’t use an “anti-spam” e-mail address that
requires the responder to modify your address. Why cause extra work for someone
who’s doing you a favor?
4799-2 AppA.F 6/11/01 9:49 AM Page 865
866
Appendixes
The Spreadsheet Page
This is my own Web site. All humility aside, this is one of best sites on the Web for
developer information. It contains files to download, developer tips, instructions
for accessing Excel Easter Eggs, an extensive list of links to other spreadsheet sites,
information about my books, and even spreadsheet jokes. The URL is:
/>This site also contains a list of errors that I’ve found in each of my books, including
the book you’re reading now. (Yes, a few errors have been known to creep into
these pages.)
Chip Pearson’s Excel pages
Chip is principal of Pearson Software Consulting, and his Web site contains dozens
of useful examples of VBA and clever formula techniques. The URL is:

Stephen Bullen’s Excel page
Stephen is an Excel developer based in the United Kingdom, and head of Business
Modeling Solutions Ltd. His Web site contains some fascinating examples of Excel
code, including a section titled “They Said It Couldn’t Be Done.” The URL is:
/>Spreadsheet FAQ
Many newsgroups have a FAQ — a list of frequently asked questions. The purpose
of FAQs is to prevent the same questions from being asked over and over. The FAQ
for the comp.apps.spreadsheets newsgroup is available at:
./faqs/spreadsheets/faq
CompuServe Forums

CompuServe offers several Excel forums, including a useful forum named Excel
Macros and VBA. You must be a CompuServe member to post to these forums, but
anyone can read them. The URL is as follows:
/>✦✦✦
Note
4799-2 AppA.F 6/11/01 9:49 AM Page 866

868
Appendixes
Table B-1 (continued)
Statement Action
DefDate Sets the default data type to date for variables that begin with a
specified letter
DefDec Sets the default data type to decimal for variables that begin with a
specified letter
DefDouble Sets the default data type to double for variables that begin with a
specified letter
DefInt Sets the default data type to integer for variables that begin with a
specified letter
DefLng Sets the default data type to long for variables that begin with a
specified letter
DefObj Sets the default data type to object for variables that begin with a
specified letter
DefSng Sets the default data type to single for variables that begin with a
specified letter
DefStr Sets the default data type to string for variables that begin with a
specified letter
DefVar Sets the default data type to variant for variables that begin with a
specified letter
DeleteSetting Deletes a section or key setting from an application’s entry in the

Windows Registry
Dim Declares an array
Do-Loop Loops
End Used by itself, exits the program; End is also used to end a block of
statements that begin with If, With, Sub, Function, Property,
Type, and Select
Enum* Declares a type for enumeration
Erase Reinitializes an array
Error Simulates a specific error condition
Event* Declares a user-defined event
Exit Do Exits a block of Do-Loop code
Exit For Exits a block of Do-For code
Exit Function Exits a Function procedure
Exit Property Exits a property procedure
Exit Sub Exits a subroutine procedure
FileCopy Copies a file
4799-2 AppB.F 6/11/01 9:49 AM Page 868
869
Appendix B ✦ VBA Statements and Functions Reference
Statement Action
For Each-Next Loops
For-Next Loops
Function Declares the name and arguments for a Function procedure
Get Reads data from a text file
GoSub Return Branches
GoTo Branches
If-Then-Else Processes statements conditionally
Implements* Specifies an interface or class that will be implemented in a class
module
Input # Reads data from a sequential text file

Kill Deletes a file from a disk
Let Assigns the value of an expression to a variable or property
Line Input # Reads a line of data from a sequential text file
Load Loads an object but doesn’t show it
Lock Unlock Controls access to a text file
Lset Left-aligns a string within a string variable
Mid Replaces characters in a string with other characters
MkDir Creates a new directory
Name Renames a file or directory
On Error Branches on an error
On GoSub Branches on a condition
On GoTo Branches on a condition
Open Opens a text file
Option Base Changes default lower limit
Option Compare Declares the default comparison mode when comparing strings
Option Explicit Forces declaration of all variables in a module
Option Private Indicates that an entire module is Private
Print # Writes data to a sequential file
Private Declares a local array or variable
Property Get Declares the name and arguments of a Property Get procedure
Property Let Declares the name and arguments of a Property Let procedure
Continued
4799-2 AppB.F 6/11/01 9:49 AM Page 869
870
Appendixes
Table B-1 (continued)
Statement Action
Property Set Declares the name and arguments of a Property Set procedure
Public Declares a public array or variable
Put Writes a variable to a text file

RaiseEvent Fires a user-defined event
Randomize Initializes the random number generator
ReDim Changes the dimensions of an array
Rem Specifies a line of comments (same as an apostrophe [‘])
Reset Closes all open text files
Resume Resumes execution when an error-handling routine finishes
RmDir Removes an empty directory
RSet Right-aligns a string within a string variable
SaveSetting Saves or creates an application entry in the Windows Registry
Seek Sets the position for the next access in a text file
Select Case Processes statements conditionally
SendKeys Sends keystrokes to the active window
Set Assigns an object reference to a variable or property
SetAttr Changes attribute information for a file
Static Changes the dimensions of an array, keeping the data intact
Stop Pauses the program
Sub Declares the name and arguments of a Sub procedure
Time Sets the system time
Type Defines a custom data type
Unload Removes an object from memory
While Wend Loops
Width # Sets the output line width of a text file
With Sets a series of properties for an object
Write # Writes data to a sequential text file
* Not available in Excel 97 and earlier editions
4799-2 AppB.F 6/11/01 9:49 AM Page 870
871
Appendix B ✦ VBA Statements and Functions Reference
Invoking Excel Functions in VBA Instructions
If a VBA function that’s equivalent to one you use in Excel is not available, you can

use Excel’s worksheet functions directly in your VBA code. Just precede the func-
tion with a reference to the
WorksheetFunction object. For example, VBA does not
have a function to convert radians to degrees. Because Excel has a worksheet func-
tion for this procedure, you can use a VBA instruction such as the following:
Deg = Application.WorksheetFunction.Degrees(3.14)
The WorksheetFunction object was introduced in Excel 97. For compatibility with
earlier versions of Excel, you can omit the reference to the
WorksheetFunction
object and write an instruction such as the following:
Deg = Application.Degrees(3.14)
There are no new VBA functions in Excel 2002.
Table B-2
Summary of VBA Functions
Function Action
Abs Returns the absolute value of a number
Array Returns a variant containing an array
Asc Converts the first character of string to its ASCII value
Atn Returns the arctangent of a number
CallByName* Executes a method, or sets or returns a property of an object
Cbool Converts an expression to a Boolean data type
Cbyte Converts an expression to a byte data type
Ccur Converts an expression to a currency data type
Cdate Converts an expression to a date data type
CDbl Converts an expression to a double data type
Cdec Converts an expression to a decimal data type
Choose Selects and returns a value from a list of arguments
Chr Converts a character code to a string
Cint Converts an expression to an integer data type
CLng Converts an expression to a long data type

Continued
Note
4799-2 AppB.F 6/11/01 9:49 AM Page 871
872
Appendixes
Table B-2 (continued)
Function Action
Cos Returns the cosine of a number
CreateObject Creates an OLE Automation object
CSng Converts an expression to a single data type
CStr Converts an expression to a string data type
CurDir Returns the current path
Cvar Converts an expression to a variant data type
CVDate Converts an expression to a date data type (for compatibility, not
recommended)
CVErr Returns a user-defined error value that corresponds to an error
number
Date Returns the current system date
DateAdd Adds a time interval to a date
DateDiff Returns the time interval between two dates
DatePart Returns a specified part of a date
DateSerial Converts a date to a serial number
DateValue Converts a string to a date
Day Returns the day of the month of a date
DDB Returns the depreciation of an asset
Dir Returns the name of a file or directory that matches a pattern
DoEvents Yields execution so the operating system can process other events
Environ Returns an operating environment string
EOF Returns True if the end of a text file has been reached
Err Returns the error message that corresponds to an error number

Error Returns the error message that corresponds to an error number
Exp Returns the base of the natural logarithms (e) raised to a power
FileAttr Returns the file mode for a text file
FileDateTime Returns the date and time when a file was last modified
FileLen Returns the number of bytes in a file
Filter Returns a subset of a string array, filtered
Fix Returns the integer portion of a number
Format Displays an expression in a particular format
4799-2 AppB.F 6/11/01 9:49 AM Page 872
873
Appendix B ✦ VBA Statements and Functions Reference
Function Action
FormatCurrency* Returns an expression formatted with the system currency symbol
FormatDateTime* Returns an expression formatted as a date or time
FormatNumber* Returns an expression formatted as a number
FormatPercent* Returns an expression formatted as a percentage
FreeFile Returns the next available file number when working with text files
FV Returns the future value of an annuity
GetAllSettings Returns a list of settings and values from the Windows Registry
GetAttr Returns a code representing a file attribute
GetObject Retrieves an OLE Automation object from a file
GetSetting Returns a specific setting from the application’s entry in the Windows
Registry
Hex Converts from decimal to hexadecimal
Hour Returns the hour of a time
IIF Evaluates an expression and returns one of two parts
Input Returns characters from a sequential text file
InputBox Displays a box to prompt a user for input
InStr Returns the position of a string within another string
InStrRev* Returns the position of a string within another string, from the end of

the string
Int Returns the integer portion of a number
Ipmt Returns the interest payment for a given period of an annuity
IRR Returns the internal rate of return for a series of cash flows
IsArray Returns True if a variable is an array
IsDate Returns True if a variable is a date
IsEmpty Returns True if a variable has not been initialized
IsError Returns True if an expression is an error value
IsMissing Returns True if an optional argument was not passed to a procedure
IsNull Returns True if an expression contains a Null value
IsNumeric Returns True if an expression can be evaluated as a number
IsObject Returns True if an expression references an OLE Automation object
Join* Combines strings contained in an array
LBound Returns the smallest subscript for a dimension of an array
Continued
4799-2 AppB.F 6/11/01 9:49 AM Page 873
874
Appendixes
Table B-2 (continued)
Function Action
LCase Returns a string converted to lowercase
Left Returns a specified number of characters from the left of a string
Len Returns the number of characters in a string
Loc Returns the current read or write position of a text file
LOF Returns the number of bytes in an open text file
Log Returns the natural logarithm of a number
LTrim Returns a copy of a string with no leading spaces
Mid Returns a specified number of characters from a string
Minute Returns the minute of a time
MIRR Returns the modified internal rate of return for a series of periodic

cash flows
Month Returns the month of a date
MonthName Returns the month, as a string
MsgBox Displays a modal message box
Now Returns the current system date and time
NPer Returns the number of periods for an annuity
NPV Returns the net present value of an investment
Oct Converts from decimal to octal
Partition Returns a string representing a range in which a value falls
Pmt Returns a payment amount for an annuity
Ppmt Returns the principal payment amount for an annuity
PV Returns the present value of an annuity
QBColor Returns an RGB color code
Rate Returns the interest rate per period for an annuity
Replace* Returns a string in which a substring is replaced with another string
RGB Returns a number representing an RGB color value
Right Returns a specified number of characters from the right of a string
Rnd Returns a random number between 0 and 1
Round Returns a rounded number
RTrim Returns a copy of a string with no trailing spaces
4799-2 AppB.F 6/11/01 9:49 AM Page 874
875
Appendix B ✦ VBA Statements and Functions Reference
Function Action
Second Returns the seconds portion of a specified time
Seek Returns the current position in a text file
Sgn Returns an integer that indicates the sign of a number
Shell Runs an executable program
Sin Returns the sine of a number
SLN Returns the straight-line depreciation for an asset for a period

Space Returns a string with a specified number of spaces
Spc Positions output when printing to a file
Split* Returns a one-dimensional array containing a number of substrings
Sqr Returns the square root of a number
Str Returns a string representation of a number
StrComp Returns a value indicating the result of a string comparison
StrConv Returns a converted string
String Returns a repeating character or string
StrReverse* Returns a string, reversed
Switch Evaluates a list of Boolean expressions and returns a value associated
with the first True expression
SYD Returns the sum-of-years’ digits depreciation of an asset for a period
Tab Positions output when printing to a file
Tan Returns the tangent of a number
Time Returns the current system time
Timer Returns the number of seconds since midnight
TimeSerial Returns the time for a specified hour, minute, and second
TimeValue Converts a string to a time serial number
Trim Returns a string without leading spaces and/or trailing spaces
TypeName Returns a string that describes the data type of a variable
UBound Returns the largest available subscript for a dimension of an array
UCase Converts a string to uppercase
Val Returns the number formed from any initial numeric characters of a
string
VarType Returns a value indicating the subtype of a variable
Continued
4799-2 AppB.F 6/11/01 9:49 AM Page 875
876
Appendixes
Table B-2 (continued)

Function Action
Weekday Returns a number indicating a day of the week
WeekdayName* Returns a string indicating a day of the week
Weekday Returns a number representing a day of the week
Year Returns the year of a date
* Not available in Excel 97 and earlier editions
✦✦✦
4799-2 AppB.F 6/11/01 9:49 AM Page 876

×