Professional Documents
Culture Documents
Here's how the function appears in the Function Arguments dialog box:
If the file is opened in Excel 2007, the argument descriptions are not displayed. If you save the
w orkbook as an XLS file, the Compatibility Checker kicks in and tells you that the function
C ontains more than 200 useful tips and
tricks for Excel 2007 | Other Excel 2007
descriptions w ill be removed.
books | Amazon link: John
Walkenbach's Favorite Excel 2007 Extracting An Email Address From Text
Tips & Tricks
C ategory: VBA Functions | [Item URL]
converted by Web2PDFConvert.com
This tip describes a VBA function that accepts a text string as input, and returns the first email
address found in the text. The figure below show s this function in use. The formula in cell B2
is:
=ExtractEmailAddress(A2)
If an email address is not found, the function returns an empty string. Also, note that it only
extracts the first email address.
The function is not very elegant. It just starts w ith the first "at symbol" it finds, and examines
the characters before and after the at symbol.
converted by Web2PDFConvert.com
I got lots of Excel w orkbooks via email. A significant number of them have some dow nright ugly
color choices. Beauty is in the eye of the beholder, but there's no excuse for making color
choices that result in illegible text.
The World W ide Web Consortium (W 3C) has created some formulas that can help you
determine if your foreground and background colors are legible: Ensure that foreground and
background color combinations provide sufficient contrast when viewed by someone
having color deficits or when viewed on a black and white screen.
To be an acceptable color combination, the Color Difference score should be 500 or greater,
and the Brightness Difference score should be 125 or greater. I used conditional formatting to
highlight values that exceed these minimums.
Column D has a simple formula that determines if both score meet the minimum requirement.
These formulas seem to w ork quite w ell. The color combination deemed Acceptable are all very
legible. Bottom line: You can't go w rong w ith black text on a w hite background. Reserve the
fancy colors for column headers, or for special areas of a w orksheet that you w ant to be
noticed.
How you can determine the current video resolution? There are tw o w ays that I'm aw are of:
1. Maximize Excel's w indow and then access the Application's W idth and Height properties
2. Use a W indow s API function
This document presents VBA code to demonstrate both of these techniques.
converted by Web2PDFConvert.com
Sub ShowAppSize()
' Maximize the window
Application.WindowState = xlMaximized
Sub DisplayVideoInfo()
vidWidth = GetSystemMetrics32(SM_CXSCREEN)
vidHeight = GetSystemMetrics32(SM_CYSCREEN)
Msg = "The current video mode is: "
Msg = Msg & vidWidth & " X " & vidHeight
MsgBox Msg
End Sub
Have you ever had to w ork w ith just the unique items in a range? If your data is in the form of
a database, you can use the Advanced Filter command to extract the unique items from a
single column. But if your data spans multiple columns, Advanced Filter w on't w ork. And the
Advanced Filter w on't do you any good if your data is in a VBA array.
In this document I present a VBA function that accepts either a w orksheet range object or a
VBA array. The function returns either:
A variant array that consists of just the unique elements in the input array or range (or)
A single value: the number of unique elements in the input array or range.
Here's the syntax for the UniqueItems function (w hich is listed at the end of this document):
UniqueItems(ArrayIn, Count)
Sub Test1()
Dim z(1 To 100)
For i = 1 To 100
z(i) = Int(Rnd() * 100)
Next i
MsgBox UniqueItems(z, True)
End Sub
converted by Web2PDFConvert.com
Example 2
The subroutine below counts the number of common elements in tw o w orksheet ranges. It
creates tw o arrays. Array1 consists of the unique items in A1:A16; Array2 consists of the
unique items in B1:B16. A nested loop counts the number of items that are in both ranges.
Sub Test2()
Set Range1 = Sheets("Sheet1").Range("A1:A16")
Set Range2 = Sheets("Sheet1").Range("B1:B16")
Array1 = UniqueItems(Range1, False)
Array2 = UniqueItems(Range2, False)
CommonCount = 0
For i = LBound(Array1) To UBound(Array1)
For j = LBound(Array2) To UBound(Array2)
If Array1(i) = Array2(j) Then _
CommonCount = CommonCount + 1
Next j
Next i
MsgBox CommonCount
End Sub
Example 3
The UniqueItems function can also be used in w orksheet formulas. The formula below returns
the number of unique items in a range:
=UniqueItems(A1:D21)
Example 4
To display the unique items in a range, you must array-enter the formula into a range of cells
(use Ctrl+Shift+Enter). The result of the UniqueItems function is a horizontal array. If you
w ould like to display the unique values in a column, you can use the TRANSPOSE function. The
formula below (w hich is array-entered into a vertical range) returns the unique items in
A1:D21.
=TRANSPOSE(UniqueItems(A1:D21,FALSE))
The Code
Option Base 1
(Thanks to Peter Atherton for suggesting the method to avoid converting blanks to zero values)
converted by Web2PDFConvert.com
Getting A List Of File Names Using VBA
C ategory: VBA Functions | [Item URL]
If your macro needs to present a list of files for the user to choose from, the easiest approach
is to use the GetOpenFileName method of the Application object. For example, the code below
displays the standard File Open dialog box. If the user selects a file, the filename is stored in
SelectedFile; if the user clicks Cancel, SelectedFile is equal to False.
FileCount = 0
FileName = Dir(FileSpec)
If FileName = "" Then GoTo NoFilesFound
Sub test()
Dim p As String, x As Variant
p = "c:/msoffice/excel/library/*.xls"
x = GetFileList(p)
Select Case IsArray(x)
Case True 'files found
MsgBox UBound(x)
Sheets("Sheet1").Range("A:A").Clear
For i = LBound(x) To UBound(x)
Sheets("Sheet1").Cells(i, 1).Value = x(i)
Next i
Case False 'no files found
MsgBox "No matching files"
End Select
End Sub
If you create custom w orksheet functions using VBA, this tip describes how to w rite efficient
converted by Web2PDFConvert.com
looping code.
This function returns the number of cells in a range that fall betw een tw o values. The first
argument is a range, the second argument is the low er comparison value, and the third
argument is the upper comparison value. If you w anted to count the number of values
betw een 1 and 5 in the range A1:A20, you could use this formula:
=CountBetween(A1:A20,1,5)
This function w orks fine in most situations. How ever, try entering the follow ing formula and see
w hat happens:
=CountBetween(A:A,1,5)
You'll find that evaluating this function seems to take forever since it w ill loop through all cells
in the range -- even those that are beyond the w orksheet's "used range."
My original approach to solving this problem w as to use the SpecialCells method to create a
subset of the input range that consisted only of nonempty cells. How ever, I discovered that
SpecialCells is off-limits inside of a w orksheet function.
I eventually learned the solution. The function below uses the Intersect function to create a
new range object that consists of the intersection of the UsedRange and the input range.
The addition of the Set statement solves the problem. You'll find that this function w orks
equally fast w ith either of these formulas:
=CountBetween(A1:A20,1,5)
=CountBetween(A:A,1,5)
This technique can be adapted to any custom w orksheet function that accepts a range
argument and loops through each cell in the range.
Computer users are accustomed to the ability to "undo" an operation. Almost every operation
you perform in Excel can be undone. If you program in VBA, you may have w ondered if it's
possible to undo the effects of a subroutine. The answ er is yes. The qualified answ er is it's not
always easy.
Making the effects of your subroutines undoable isn't automatic. Your subroutine w ill need to
store the previous state so it can be restored if the user choose the Edit Undo command. How
you do this w ill vary, depending on w hat the subroutine does. In extreme cases, you might
need to save an entire w orksheet. If your subroutine modifies a range, for example, you need
only save the contents of that range.
The code below demonstrates how to enable the Edit Undo command after a subroutine is
executed. The subroutine itself is very simple: it simply inserts a 0 into every cell in the current
range selection. The bulk of the code is used to save the contents of the current selection.
Trying it out
To try out this example code:
converted by Web2PDFConvert.com
3. Select the range and execute the ZeroRange subroutine. The cells w ill be replaced w ith
zeros.
4. Select the Edit Undo command. The original contents of the selection w ill be restored.
How it works
The OldSelection array stores the cell address and the cell contents (using a custom data
type). Notice that this array is declared as a Public variable so it's available to all subroutines.
The last statement in the ZeroRange subroutine specifies the text to display in the Undo
menu, and the subroutine to call if this command is selected. The UndoZero routine loops
through the OldSelection array and restores the values to their appropriate cells. Notice that I
also store the w orkbook and w orksheet -- w hich ensures that the correct cells w ill be restored
even if the user sw itches out of the original w orksheet.
Sub ZeroRange()
' Inserts zero into all selected cells
Sub UndoZero()
' Undoes the effect of the ZeroRange sub
Application.ScreenUpdating = False
' Make sure the correct workbook and sheet are active
OldWorkbook.Activate
OldSheet.Activate
converted by Web2PDFConvert.com
End Sub
This tip presents tw o useful VBA functions that can be used in w orksheet formulas.
LASTINCOLUMN returns the contents of the last non-empty cell in a column; LASTINROW
returns the contents of the last non-empty cell in a row . Each function accepts a range as its
single argument. The range argument can be a complete column (for LASTINCOLUMN) or a
complete row (for LASTINROW ). If the supplied argument is not a complete column or row , the
function uses the column or row of the upper left cell in the range. For example, the follow ing
formula returns the last value in column B:
=LASTINCOLUMN(B5)
The formula below returns the last value in row 7:
=LASTINROW(C7:D9)
You'll find that these functions are quite fast, since they only examine the cells in the
intersection of the specified column (or row ) and the w orksheet's used range.
Multifunctional Functions
C ategory: VBA Functions | [Item URL]
This tip describes a technique that may be helpful in some situations - making a single
w orksheet function act like multiple functions. For example, the VBA listing below is for a
custom function called StatFunction. It takes tw o arguments: the range (rng), and the
operation (op). Depending on the value of op, the function w ill return any of the follow ing:
AVERAGE, COUNT, MAX, MEDIAN, MIN, MODE, STDEV, SUM, or VAR.
For example, you can use this function in your w orksheet as follow s:
=STATFUNCTION(B1:B24,A24)
The result of the formula depends on the contents of cell A24 -- w hich should be a string such
converted by Web2PDFConvert.com
as Average, Count, Max, etc. You can adapt this technique for other types of functions.
Page 1 of 3 pages
[Next page]
converted by Web2PDFConvert.com