Excel User Forms Tips 2
Excel User Forms Tips 2
In particular, the user interface for Excel This tip demonstrates a technique to display a dialog box that allow s the user to select a color.
2007 (and later), is vastly different from
its predecessors. Therefore, the menu How it works
commands listed in older tips, will not
correspond to the Excel 2007 (and later) The example file contains the follow ing:
user interface.
A UserForm (UserForm1) that contains a dialog box w ith 56 buttons.
All Tips A Class Module (Class1) that defines a ColorButton Class.
List all tips, by category A VBA module (Module1) that contains a function (GetAColor).
Browse all tips Tw o example subroutines that demonstrate the GetAColor function.
The GetAColor function sets up the dialog box and display it (see the figure below ). The
Browse Tips by Category function returns the color value of the selected button. If the user clicks Cancel, the GetAColor
function returns False. As the user moves the mouse pointer over the color buttons, the Color
General
Sample image displays the color.
Formatting
Formulas
Charts & Graphics
Printing
General VBA
CommandBars & Menus
UserForms
VBA Functions
Advanced Search
Using the function
To use the GetAColor function in your ow n w orkbooks, export UserForm1, Module1, and
Tip Books Class1, and then import them into your w orkbook. W rite your ow n subroutine that calls the
Needs tips? Here are two books, with GetAColor function.
nothing but tips:
Displaying A Chart In A Userform
C ategory: UserForms | [Item URL]
One of my favorite Excel tricks is to display a chart in a UserForm. You might think that this
w ould be easy: Just add a linked picture of the chart to the UserForm. Unfortunately, that's not
possible.
This tip describes a w orkaround that involves saving the chart as a GIF file, and then
C ontains more than 200 useful tips and displaying the GIF in an Image control. This ensures that the UserForm alw ays displays the
tricks for Excel | Other Excel 2003
books | Amazon link: John
current version of the chart.
Walkenbach's Favorite Excel Tips &
Tricks You might notice a slight delay as the chart is saved and then retrieved. On a fast system,
how ever, this delay is barely noticeable.
converted by Web2PDFConvert.com
C ontains more than 200 useful tips and
tricks for Excel 2007 | Other Excel 2007
books | Amazon link: John
Walkenbach's Favorite Excel 2007
Tips & Tricks
How it works
To set this up:
Image1.Picture = LoadPicture(Fname)
You probably know that the Insert Hyperlink command (or Ctrl+K) lets you insert a hyperlink
into any cell. But if you've tried to add a hyperlink to a UserForm, you may have come up
empty-handed.
There is no direct w ay to add a hyperlink to a UserForm, but you can simulate one by using the
techniques described here. The figure below show s an example.
1. Add a Label object and enter some text for its Caption
2. Make the Label blue and underlined so it resembles a typical hyperlink. You might also
w ant to set its font to Courier New .
3. None of the standard mouse pointers resembles a pointing hand, so set the Label's
converted by Web2PDFConvert.com
MousePointer property to: 99 - fmMousePointerCustom
4. Specify the cursor file for the Label's MouseIcon image. If you don't have a cursor file that
resembles a pointing hand, click here to dow nload a file named hand.cur.
5. Double-click the Label and enter an event-handler subroutine for its Click event. The
Follow Hyperlink method is w hat makes it w ork. Here's an example of such a subroutine:
Private Sub Label1_Click()
Link = "http://www.whitehouse.gov"
On Error GoTo NoCanDo
ActiveWorkbook.FollowHyperlink Address:=Link, NewWindow:=True
Unload Me
Exit Sub
NoCanDo:
MsgBox "Cannot open " & Link
End Sub
To create a "mail to" hyperlink, use a statement like this:
Link = "mailto:[email protected]"
Many VBA programmers don't realize it, but it's possible to create a UserForm using VBA. In
addition, you can w rite code to add controls to the UserForm, and even create event-handler
procedures in the UserForm's code module.
This is possible because of the Visual Basic Integrated Development Environment (the VBIDE).
The VBIDE is described in the online help, but it's very sketchy and provides few examples. The
example in this document may help you understand how the VBIDE w orks.
Contrary to w hat you might expect, this process is very fast -- virtually instantaneous on my
system.
The example below is a simple subroutine that demonstrates the use of GetOption. It creates
a 12-item array (Ops) that consists of the month names. It then calls the GetOption function,
passing the follow ing arguments: The 12-item array, a literal 1 (the first item is the default),
and a literal string ("Select a month").
Sub DemoGetOption()
Dim Ops(1 To 12) As String
' Create an array of month names
For i = 1 To 12
Ops(i) = Format(DateSerial(1, i, 1), "mmmm")
converted by Web2PDFConvert.com
Next i
UserChoice = GetOption(Ops, 1, "Select a month")
MsgBox UserChoice
End Sub
The figure below show s the UserForm as it is displayed to the user. W hen the user clicks OK,
the GetOption function returns a value betw een 1 and 12. If the user clicks Cancel, the
function returns False,
View or Download
Click the link below to dow nload modGetOption.Bas. This is a text file that can be imported
directly into a VBA project. In the VB Editor, activate your project, then select File Import File (or
press Ctrl+M). Locate the modGetOption.Bas file and click OK. The module w ill be added to
your project.
NOTE: It is not necessary to add a reference to the Visual Basic Extensibility Library in order to
use this function.
Every UserForm that you create contains a Close button ("x") in its title bar. Clicking the Close
button (or pressing Alt+F4) closes the UserForm.
In some cases, you may not w ant to allow the user to close the UserForm in this manner.
There's no easy w ay to disable the Close button, but a few lines of VBA code w ill prevent it
from being used.
Activate the code module for your UserForm, and enter the follow ing procedure:
Most developers know that it's possible to insert dialog box controls (such as buttons and
checkboxes) directly on a w orksheet. This topic, how ever, is the source of a great deal of
confusion. This tip attempts to clarify some of the issues related to using controls on
w orksheets.
Two types of controls
First, it's important to understand that Excel supports tw o general types of controls:
ActiveX Controls
Excel Controls
These tw o types of controls are described in the table below .
converted by Web2PDFConvert.com
ActiveX Controls Excel Controls
Excel versions 97, 2000 5, 95, 97, 2000
W hich toolbar? Control Toolbox Forms
CheckBox, TextBox, CommandButton,
Label, GroupBox, Button, CheckBox,
OptionButton, ListBox, ComboBox,
Controls available OptionButton, ListBox, ComboBox,
ToggleButton, SpinButton, ScrollBar,
ScrollBar, Spinner
Label, Image
Macro code
In the code module for the Sheet In any standard VBA module
storage
Corresponds to the control name
Macro name Any name you specify.
(e.g., CommandButton1_Click)
Correspond to... UserForm controls Dialog Sheet controls
Customization Extensive, using the Properties box Minimal
Respond to
Yes Click or Change events only
events
To customize the control, right-click it and select Properties. This displays the Properties
w indow . Each control has its ow n set of properties.
Some ActiveX controls can be connected to a cell (i.e., the LinkedCell property). Other controls
can receive information from a range. For example, a ListBox control can get its list data from
the ListFillRange property. Consult the online help for complete details regarding the
properties for each control.
Each ActiveX control also triggers events. For example, a CommandButton control generates a
Click event. You can w rite an event-handler Sub procedure to respond to the events. The
procedure below , for example, displays a message box w hen a CommandButton (named
CommandButton1) is clicked:
Right-click the control to access the Format dialog box. Any customizations to the control are
made using this dialog box. Formatting options are limited. To assign a macro to the control,
right-click it and select Assign Macro. Excel controls can execute any macros.
I need to get just a few pieces of information and a UserForm seems like overkill. Are
there any alternatives?
Yes, check out VBA's MsgBox function and its InputBox function. Alternatively, you might w ant
to use Excel's InputBox method.
There is no easy w ay to do this, because each CommandButton has its ow n Click event
procedure. One solution is to call another subroutine from each of the CommandButton_Click
subroutines. Another solution is to use a class module to create a new class. Follow this link
for an example.
converted by Web2PDFConvert.com
There is not direct w ay to do this. One solution is to w rite that saves the chart to a GIF file,
and then loads the GIF file into an Image control. Follow this link for an example.
How can I remove the "x" from the title bar of my UserForm? I don't want the user to click
that button to close the form.
You can't remove the Close button on a UserForm's title bar. How ever, you can intercept all
attempts to close the UserForm by using a UserForm_QueryClose event procedure in the code
module for the UserForm. The example below does not allow the user to close the form by
clicking the Close button.
I've created a UserForm, and the controls are linked to cells on the worksheet. Is this the
best way to do this?
In general, you should avoid using links to w orksheet cells unless you absolutely must. Doing
so can slow your application dow n, because the w orksheet is recalculated 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,
but I can't figure out how to do it with Excel.
You can't create a control array, but you can create an array of Control objects. The code
below creates an array consisting of all CommandButton controls.
Yes, the Hide method keeps the UserForm in memory, but makes it invisible. The Unload
statement unloads the UserForm.
Excel 97 UserForms are modal -- w hich means that the form must be dismissed before you can
do anything else. Excel 2000, how ever, supports modeless UserForms.
I need to display a progress indicator (like those used during software installation) while
a lengthy process is being executed. How can I do this?
You can do this w ith a UserForm. Follow this link for an example.
How can I get 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 statement. This displays a "file open"
dialog box in w hich 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,
how ever, is to set up your ListBox to use tw o columns.
Most (but not all) of Excel's dialog boxes can be displayed by using the Application.Dialogs
converted by Web2PDFConvert.com
method. For example, the follow ing statement displays the dialog box that lets you format
numbers in cells:
Application.Dialogs(xlDialogFormatNumber).Show
Use the Object Brow ser to display a list of the constants for the built-in dialog boxes. Press F2
from the VBE, then select the Excel library and then the Constants object. The
Method/Properties list w ill display the constants for the built-in dialog boxes (they all begin
w ith xlDialog).
I tried the technique in the preceding question and received an error message. Why is
that?
The Dialogs method w ill fail if the context isn't appropriate. For example, if you attempt to
display the Chart Type dialog box (xlDialogChartType) w hen a chart is not activated, you'll get
an error message.
Every time I create a UserForm, I go through the steps of adding an OK button and a
Cancel button. Is there a way to get these controls to appear automatically?
Yes, create a UserForm set up w ith the controls you use most often. Then select File - Export
File to save the UserForm. W hen you w ant to add a new form to another project, select File -
Import File.
No. The closest you can get is to make the dialog box's caption blank by setting the Caption
property to an empty string.
I recorded some VBA code to print to a file. However, there seems to be no way to supply
the filename in my code. No matter what I try, I keep getting the prompt to supply a
filename.
This w as a common problem that w as corrected in Excel 2000. In Excel 2000, you can provide
a PrToFileName argument for the PrintOut method. Here's an example:
ActiveSheet.PrintOut _
PrintToFile:=True, PrToFileName:="test.prn"
Controls added to a UserForm do nothing unless you w rite event-handler procedures for them.
I wrote a subroutine named Workbook_Open, but it doesn's get executed when the
workbook is opened.
The most likely cause is that your subroutine is located in a normal VBA module. Workbook
event procedures must be located in the code module for the ThisWorkbook object.
Can I create a custom dialog box that displays in the same size, regardless of the video
display resolution?
You can, but it's probably not w orth the effort. You can w rite code to determine the video
resolution, and then make use of the Zoom property of a UserForm to change its size. The
normal w ay to deal w ith this sort of thing is to simply design your UserForm for a 640x480
display.
Is it possible to create a UserForm box that lets the user select a range in a worksheet by
pointing?
Yes, you can set the UserForm's Left and Top properties. But in order for these to be effective
you need to set the StartUpPosition property to 0.
Right-click any sheet tab in a w orkbook and select Insert from the shortcut menu. In the Insert
dialog box, select MS Excel 5.0 Dialog.
Page 2 of 2 pages
[Previous page]
converted by Web2PDFConvert.com
converted by Web2PDFConvert.com