Advanced Search
Tip Books
Needs tips? Here are two books, with
nothing but tips:
converted by Web2PDFConvert.com
or a control that has a Picture property).
3. Make sure the Properties w indow is displayed (press F4 it it's not).
4. Click the Picture item. By default, this displays "(None)" as in the figure above.
5. Press Ctrl+V to paste the image on the Clipboard to the control.
More
Importantly, the picture that you paste to a control need not be stored in a file. Any picture
that can be copied to the Clipboard can be pasted to an object's Picture property. And this
includes charts stored in a w orksheet. The trick here is to copy the chart as a picture: Click the
chart, press Shift, and choose Copy Picture from Excel's Edit menu. Once copied, you can paste
the picture of the chart to your UserForm control.
W hen pasting a chart, it's important to understand that the picture is not linked to the original
chart. So if the chart changes, the picture w ill not change.
Displaying Help
C ategory: General VBA / UserForms | [Item URL]
This tip describes a useful technique that lets you display a series of help topics in an Excel
w orkbook.
How it works
The technique described here uses a UserForm, and the UserForm has the follow ing controls
(see the Figure below ):
A DropDow n control (w hich displays the current help topic title)
A Label control that displays the help topic text
A Frame control. The label is inside of the frame to allow scrolling if all of the text isn't
visible.
Three buttons: Previous, Next, and Exit
The help topics are contained on a w orksheet, and the VBA code simply reads the text in the
w orksheet and transfers it to the UserForm. The user can select a help topic from the
DropDow n, or view the topics sequentially using the Previous and Next buttons.
One of the most useful features in Excel is the ability to create custom dialog boxes
(UserForms). Before embarking on this task, ask yourself if a custom dialog box is really
necessary. In some cases you may be able to use one of the follow ing options to get user
converted by Web2PDFConvert.com
input:
VBA's MsgBox function
VBA's InputBox function (alw ays returns a string)
Excel's InputBox function (you can specify the type of data returned)
Excel's GetOpenFilename method
Excel's GetSaveAsFilename method
Excel's FileDialog object (Excel 2002 only)
And, don't forget that your VBA code can display most of Excel's built-in dialog boxes. For
example, the follow ing subroutine displays the Move or Copy dialog (used to move or copy a
sheet):
Sub ShowMoveCopy()
Application.Dialogs(xlDialogWorkbookMove).Show
End Sub
W hen designing your userForm, a good rule of thumb is to make the dialog boxes look and
w ork like those that are built into Excel. If you're a beginner, you may find it instructive to try to
recreate a particular Excel dialog box. You may find a few situations in w hich a built-in dialog
box can't be recreated exactly.
Checklist
Before you unleash your UserForm, give it one final check using the follow ing checklist.
Selecting A Directory
C ategory: UserForms | [Item URL]
If your Excel application needs to prompt the user for a directory, you may have been
surprised to discover that there is no direct w ay to do this. You can use the GetOpenFileName
method to display a dialog that prompts for a file name, but there is no w ay to display a dialog
box that show s only directories.
In this document I present a function (named GetDirectory) that displays the dialog box show n
below , and returns a string that represents the selected directory. If the user clicks cancel, the
function returns an empty string.
converted by Web2PDFConvert.com
The GetDirectory function takes one argument, w hich is optional. This argument is a string that
w ill be displayed in the dialog box. If the argument is omitted, the dialog box displays Select a
folder as the message.
Option Explicit
Public Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Sub Test()
Dim Msg As String
Msg = "Please select a location for the backup."
MsgBox GetDirectory(Msg)
End Sub
converted by Web2PDFConvert.com
' Parse the result
path = Space$(512)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
GetDirectory = Left(path, pos - 1)
Else
GetDirectory = ""
End If
End Function
Sub Test()
Dim Msg As String
Msg = "Please select a location for the backup."
MsgBox GetDirectory(Msg)
End Sub
NOTE: If you use Excel 2002 or later you can prompt the user to select a directory by using
the FileDialog object. The advantage is that you can specify a starting directory.
A common question among Excel developers is, How can I use a custom dialog box to display the
progress of a lengthy macro?
This document describes how to create an attractive progress indicator w ith minimal effort.
converted by Web2PDFConvert.com
Sub Main()
' Inserts random numbers on the active worksheet
Dim Counter As Integer
Dim RowMax As Integer, ColMax As Integer
Dim r As Integer, c As Integer
Dim PctDone As Single
Sub ShowDialog()
UserForm1.LabelProgress.Width = 0
UserForm1.Show
End Sub
How it works
W hen you execute the Show Dialog subroutine, the Label object's w idth is set to 0. Then the
Show method of the UserForm1 object displays the dialog box. W hen the dialog box is
displayed, its Activate event is triggered, w hich executes the Main subroutine. The Main
subroutine periodically updates the w idth of the Label. Notice the DoEvents statement.
W ithout this statement, changes to the Label are not visible. Before the subroutine ends, the
last statement unloads the UserForm object.
Caveat
This is definitely a slick technique, but you should be aw are that it may slow dow n your macro
a bit due to the extra overhead of updating the progress indicator. In many cases, how ever, it
is not even noticeable.
If you've w orked w ith UserForms, you've undoubtedly noticed that inserting a new UserForm
results in an empty dialog box. You might prefer to add a UserForm that already has some
controls on it (for example, an OK button and a Cancel button).
In this document I describe a simple technique that lets you create a new "default" UserForm
that contains these tw o buttons. The procedure can be adapted for other controls.
Name: OKButton
converted by Web2PDFConvert.com
Caption: OK
Default: True
Name: CancelButton
Caption: Cancel
Cancel: True
9. Double-click the Cancel button to activate the Code w indow for the UserForm.
10. Modify the CancelButton_Click subroutine as follow s:
Private Sub Cancel_Button_Click()
Unload Me
End Sub
W hen you create a UserForm, every control on the form must have its ow n event handler
procedure. For example, if a UserForm has 12 CommandButtons, you need 12 procedures to
handle the click events for those buttons.
This tip describes a w ay around this limitation by using a Class Module to define a new class.
Procedure
1. Create your UserForm as usual, and add several CommandButtons.
2. Insert a Class Module and enter the follow ing code. You w ill need to customize the
ButtonGroup_Click subroutine.
Public WithEvents ButtonGroup As CommandButton
3. Insert a normal module and enter the follow ing code. In this code, I exclude a button
named OKButton from the "button group." Therefore, clicking the OK Button does not
execute the ButtonGroup_Click subroutine.
Option Explicit
Dim Buttons() As New Class1
Sub ShowDialog()
Dim ButtonCount As Integer
Dim ctl As Control
converted by Web2PDFConvert.com
ButtonCount = ButtonCount + 1
ReDim Preserve Buttons(1 To ButtonCount)
Set Buttons(ButtonCount).ButtonGroup = ctl
End If
End If
Next ctl
UserForm1.Show
End Sub
4. Execute the Show Dialog subroutine to display the UserForm. Clicking any of the
CommandButtons (except the OKButton) executes the ButtonGroup_Click subroutine.
Note: To use this technique w ith other types of controls, change the W ithEvents statement.
For example:
W hen you display a list of items in a ListBox, you generally don't w ant to show duplicate items.
This tip describes a clever w ay of filling a UserForm w ith unique items from a list. This
technique is adapted from a tip by J.G. Hussey, published in Visual Basic Programmer's Journal.
How it works
This tip uses a Collection object, and relies on the fact that VBA generates an error if you
attempt to add an item to a collection w hen the item already exists in the collection. The trick
is to build the collection by adding all items to it, and ignore the errors that may occur. The
result is a collection of unduplicated items.
Example
I created an example to demonstrate the technique. The items (105 of them) are stored in
Column A of a w orksheet. Many of these items are duplicated. The RemoveDuplicates
subroutine, listed below , builds a collection that consists of the unique items in the list. It then
transfers the items to a ListBox on a UserForm.
Listing
Follow ing is the VBA listing.
Option Explicit
' This example is based on a tip by J.G. Hussey,
' published in "Visual Basic Programmer's Journal"
Sub RemoveDuplicates()
Dim AllCells As Range, Cell As Range
Dim NoDupes As New Collection
Dim i As Integer, j As Integer
Dim Swap1, Swap2, Item
converted by Web2PDFConvert.com
Swap1 = NoDupes(i)
Swap2 = NoDupes(j)
NoDupes.Add Swap1, before:=j
NoDupes.Add Swap2, before:=i
NoDupes.Remove i + 1
NoDupes.Remove j + 1
End If
Next j
Next i
This tip contains a VBA subroutine that displays a dialog box that contains the names of all
non-empty w orksheets in the active w orkbook. The names are displayed as checkboxes. The
user can select w hich sheets to print, and click OK. The macro then prints the selected
w orksheets.
This subroutine is rather unusual since it creates the dialog box on the fly, and then deletes it
after it is dismissed.
The code below prints the selected w orksheets, but this general technique can be adapted to
other situations in w hich you need the user to specify one or more sheets in a w orkbook.
Although this procedure uses an Excel 5/95 Dialog Sheet, it w ill also w ork w ith later versions of
Excel. By the w ay, this is a rare example of how using a Dialog Sheet is easier than using a
UserForm. Creating a UserForm on the fly is much more difficult, but it is possible.
Sub SelectSheets()
Dim i As Integer
Dim TopPos As Integer
Dim SheetCount As Integer
Dim PrintDlg As DialogSheet
Dim CurrentSheet As Worksheet
Dim cb As CheckBox
Application.ScreenUpdating = False
converted by Web2PDFConvert.com
SheetCount = 0
TopPos = 40
For i = 1 To ActiveWorkbook.Worksheets.Count
Set CurrentSheet = ActiveWorkbook.Worksheets(i)
' Skip empty sheets and hidden sheets
If Application.CountA(CurrentSheet.Cells) <> 0 And _
CurrentSheet.Visible Then
SheetCount = SheetCount + 1
PrintDlg.CheckBoxes.Add 78, TopPos, 150, 16.5
PrintDlg.CheckBoxes(SheetCount).Text = _
CurrentSheet.Name
TopPos = TopPos + 13
End If
Next i
End With
End If
Next cb
End If
Else
MsgBox "All worksheets are empty."
End If
If PrintDlg.Show Then
For Each cb In PrintDlg.CheckBoxes
If cb.Value = xlOn Then
Worksheets(cb.Caption).Select Replace:=False
End If
Next cb
ActiveWindow.SelectedSheets.PrintOut copies:=1
ActiveSheet.Select
End If
Page 1 of 2 pages
converted by Web2PDFConvert.com
Page 1 of 2 pages
[Next page]
converted by Web2PDFConvert.com