Professional Documents
Culture Documents
converted by Web2PDFConvert.com
The SheetExists Function
Private Function SheetExists(sname) As Boolean
' Returns TRUE if sheet exists in the active workbook
Dim x As Object
On Error Resume Next
Set x = ActiveWorkbook.Sheets(sname)
If Err = 0 Then SheetExists = True _
Else SheetExists = False
End Function
You probably know that you find out w hen a file w as created by right-clicking the file name in
the W indow s Explorer, clicking Properties on the context menu.
If you're in Excel, you can determine the creation date of the active w orkbook by selecting
Properties from the File menu. The file creation date appears tw ice in the Properties dialog
box: on the General tab, and on the Statistics tab. In many cases these tw o dates are
different!
The file creation date and time on the Statistics tab is w hen the file w as originally created.
The file creation date and time on the General tab is w hen the file w as first saved on your
computer.
You can use the VBA statement below to examine the actual file creation date and time (the
date and time show n in the Statistics tab):
MsgBox ActiveWorkbook.BuiltinDocumentProperties.Item _
("Creation date").Value
If you'd like to determine the date and time that the file w as saved on your computer, you can
use the routines listed below . The result is the same date and time that is displayed in the
General tab of the Properties dialog box.
You'll need to copy all of the code below to a module. The Show File subroutine displays the file
creation date and time for the active w orkbook. You can easily customize this subroutine to
show the creation date for any file.
VBA Code
'32 bit Windows declarations
Public Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" _
(ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Public Declare Function FileTimeToSystemTime Lib "kernel32" _
(lpFileTime As FILETIME, lpSystemTime As SYSTEMTIME) As Long
Declare Function FileTimeToLocalFileTime Lib "kernel32" _
(lpFileTime As FILETIME, lpLocalFileTime As FILETIME) As Long
converted by Web2PDFConvert.com
wMilliseconds As Long
End Type
The W indow s registry is a central storehouse that is used by applications to store information
such as user preferences. Prior to Excel 97, accessing the registry required API calls. Excel 97
(and later versions) includes tw o handy VBA functions:
GetSetting: Retrieves a setting from the registry
SaveSetting: Saves a setting to the registry
These tw o functions are described in the online help, so I w on't cover the details here.
How ever, it's important to understand that these functions w ork only w ith the follow ing key
name:
converted by Web2PDFConvert.com
An example
The subroutine below , w hich is stored in the code module for the ThisWorkbook object,
demonstrates the GetSetting and SaveSetting functions. This subroutine is executed w hen the
w orkbook is opened. It retrieves tw o bits of information: the number of times the w orkbook
has been opened; and the date and time the file w as last opened. This information is
displayed in a message box.
In some situations you may need to determine the type of data in a cell. Excel provides a
number of built-in functions that can help. These include ISTEXT, ISLOGICAL, and ISERROR. In
addition, VBA includes functions such as IsEmpty, IsDate, and IsNumeric.
The CellType function (VBA code is listed below ) accepts a range argument and returns a string
that describes the data type of the upper left cell in the range. The function returns one of the
follow ing strings: Blank, Text, Logical, Error, Date, Time, or Value.
converted by Web2PDFConvert.com
Using the CellType function
To use this function in a w orskheet, just copy the code and paste it to a module. Then, you can
enter a formula such as:
=CellType(A1)
You may have discovered that Excel's support for "3D w orkbooks" is limited. For example, if
you need to refer to a different w orksheet in a w orkbook, you must include the w orksheet's
name in your formula. This is not a big problem -- until you attempt to copy the formula across
other w orksheets. The copied formulas continue to refer to the original w orksheet name.
This tip contains a VBA function (named SHEETOFFSET) that lets you address w orksheets in a
relative manner. For example, you can refer to cell A1 on the previous w orksheet using this
formula:
=SHEETOFFSET(-1,A1)
Then, you can copy this formula to other sheets and the relative referencing w ill be in effect in
all of the copied formulas.
=SHEETOFFSET(2,C1)
The first argument represents the sheet offset, and it can be positive, negative, or 0.
The second argument must be a reference to a single cell. If the first argument is 0, the
cell reference must not be the same as the cell that contains the formula. If so, you'll
generate a circular reference error.
NOTE: Be careful if your w orkbook contains non-w orksheet sheets (for example, chart sheets).
If the offset argument results in a reference to a chart sheet, the function w ill display an error.
In some situations, you may need to determine if a particular range is contained w ithin
another range. For example, you may need to determine if the active cell is in a particular
range.
The InRange function, listed below , accepts tw o arguments (both Range objects). The function
returns True if the first range is contained in the second range. Notice that the function checks
to make sure that the tw o range arguments are contained in the same sheet and in the same
w orkbook.
You can use the InRange function in your VBA code, or in a w orksheet function.
converted by Web2PDFConvert.com
InRange = True
End If
End If
End If
End Function
An Example
Listed below is a simple example that uses the InRange function. The subroutine prompts the
user to select a range, and then checks the range using the InRange function. If the user's
selection is not w ithin A1:E20, the prompt appears again.
Sub Test()
Dim ValidRange As Range, UserRange As Range
Dim SelectionOK As Boolean
SelectionOK = True
Else
MsgBox "Select a range within " & ValidRange.Address
End If
Loop
End Sub
Every w orkbook and sheet has a corresponding code module. These code modules can contain
VBA code to handle w orkbook or sheet-level events. For example, a w orkbook code module
(named ThisWorkbook by default) might have a subroutine declared as follow s:
Similarly, code modules for w orksheets can contain subroutines to handle w orksheet event
such as Activate, Deactivate, Change, etc.
Listed below are tw o custom VBA functions that you can use to determine if the code module
for a particular w orkbook or w orksheet contains any code.
converted by Web2PDFConvert.com
Else
SheetHasVBACode = True
End If
End Function
An Example
The example below demonstrates a practical use of the SheetHasVBACode function. The
DeleteBlankSheets subroutine deletes all blank sheets in the active w orkbook -- but only if the
sheet does not contain any VBA code.
Sub DeleteBlankSheets()
Dim sht As Worksheet
On Error GoTo ErrHandler
' Avoid Excel's confirmation prompt
Application.DisplayAlerts = False
' Loop through each sheet
For Each sht In ActiveWorkbook.Worksheets
' Is non-blank cell count zero?
If Application.CountA(sht.Cells) = 0 Then
' Don't try to delete the last sheet
If ActiveWorkbook.Sheets.Count <> 1 Then
' Don't delete sheet if it has VBA code
If Not SheetHasVBACode(sht) Then
sht.Delete
End If
End If
End If
Next sht
Exit Sub
ErrHandler:
MsgBox sht.Name & Chr(13) & Chr(13) & Error(Err)
End Sub
Soundex is an indexing system that translates a name into a 4-digit code consisting of one
letter and three numbers. The advantage of Soundex is its ability to locate names by the w ay
they sound, rather than by exact spelling. For example, consider the name Maris. This name
has a Soundex code of M620. Other variations on this name (such as Mares, Marriss, Mariss,
and Mairis) all have the same Soundex code.
Soundex Rules
1. Each Soundex code has exactly four alphanumeric characters (1 letter and 3 numbers)
2. The first letter of the name is alw ays the first character of the Soundex code.
3. The remaining three digits are defined from the name using the Soundex Key Codes listed
below .
4. Adjacent letters in the name w hich have the same Soundex Key code number are
assigned a single digit.
5. If the name is not long enough to yield four characters,the code is padded w ith zeros.
Code Letter
1 BFPV
2 C GJKQ SXZ
3 DT
4 L
5 MN
6 R
No code AEHIOUYW
The function can be used in a w orksheet formula, or called from a VBA procedure. The
SOUNDEX function is listed below . Notice that this function calls another function named
Category.
converted by Web2PDFConvert.com
Function SOUNDEX(Surname As String) As String
' Developed by Richard J. Yanco
' This function follows the Soundex rules given at
' http://home.utah-inter.net/kinsearch/Soundex.html
Surname = UCase(Surname)
Result = Left(Surname, 1)
For Location = 2 To Len(Surname)
Result = Result & Category(Mid(Surname, Location, 1))
Next Location
' If category of 1st letter equals 2nd character, remove 2nd character
converted by Web2PDFConvert.com
Case c = "L"
Category = "4"
Case c Like "[MN]"
Category = "5"
Case c = "R"
Category = "6"
Case Else 'This includes H and W, spaces, punctuation, etc.
Category = ""
End Select
End Function
The demo file (linked above) contains a list of more than 4,000 names. You can search for a
name in the list, and specify an exact match or an approximate match.
If you choose an approximate match, you'll get a list of names that have the same Soundex
code as the name you're searching for.
Your VBA procedure might need to present the user w ith a list of fonts to choose from. Or, you
may need to determine if a particular font is installed. The simplest w ay to access the installed
font list is to get the fonts from the Font control on the Formatting toolbar. The Font control
contains a dropdow n list of installed fonts, and you can w rite VBA code to retrieve that list
from the control.
Sub ShowInstalledFonts()
Set FontList = Application.CommandBars("Formatting").FindControl(ID:=1728)
converted by Web2PDFConvert.com
End Sub
Is a font installed?
The function below uses the same technique as the Show InstalledFonts procedure. it returns
True if a specified font is installed.
For i = 0 To FontList.ListCount - 1
If FontList.List(i + 1) = sFont Then
FontIsInstalled = True
On Error Resume Next
TempBar.Delete
Exit Function
End If
Next i
The statement below demonstrates how to use this function in a VBA procedure. It displays
True in a message box if the user's system contains the Comic Sans MS font.
VBA does not include a method to retrieve a value from a closed file. You can, how ever, take
advantage of Excel's ability to w ork w ith linked files.
This tip contains a VBA function that retrieves a value from a closed w orkbook. It does by
calling an XLM macro.
converted by Web2PDFConvert.com
C:.
Sub TestGetValue()
p = "c:\XLFiles\Budget"
f = "Budget.xls"
s = "Sheet1"
a = "A1"
MsgBox GetValue(p, f, s, a)
End Sub
Another example is show n below . This procedure reads 1,200 values (100 row s and 12
columns) from a closed file, and places the values into the active w orksheet.
Sub TestGetValue2()
p = "c:\XLFiles\Budget"
f = "Budget.xls"
s = "Sheet1"
Application.ScreenUpdating = False
For r = 1 To 100
For c = 1 To 12
a = Cells(r, c).Address
Cells(r, c) = GetValue(p, f, s, a)
Next c
Next r
Application.ScreenUpdating = True
End Sub
Caveat
In order for this function to w ork properly, a w orksheet must be active in Excel. It w ill generate
an error if all w indow s are hidden, or if the active sheet is a Chart sheet.
Page 2 of 3 pages
[Previous page] [Next page]
converted by Web2PDFConvert.com