You are on page 1of 13

Advertisement

PowerBasic vs VisualBasic Faster. No Run-Times. No Bloat! CGI, Macros, ASM, Reg Expressions www.powerbasic.com
Lipid Analytical Services MS/MS, NMR, Reference Standards Stability Testing, Method Dev. www.avantilipids.com
Java Persistence Tools OpenJPA, Toplink, Hibernate Suppt No Lock-in, Eclipse-Based www.myeclipseide.com

Understanding VBA Functions and Their Uses


By John Walkenbach
A function performs a calculation and returns a single value. The SUM function adds the sum of a range
of values. The same holds true for functions used in your VBA expressions: Each function does its thing
and returns a single value.
The functions you use in VBA can come from three sources:
• Built-in functions provided by VBA
• Worksheet functions provided by Excel
• Custom functions that you (or someone else) write, using VBA
VBA provides numerous built-in functions. Some of these functions take arguments and some do not.

VBA function examples


Here are a few examples of using VBA functions in code. Note the use of the MsgBox function to display
a value in a message box. Yes, MsgBox is a VBA function — a rather unusual one, but a function
nonetheless. This useful function displays a message in a pop-up dialog box.
Displaying the system date
The first example uses VBA's Date function to display the current system date in a message box:
Sub ShowDate()
MsgBox Date
End Sub
Notice that the Date function doesn't use an argument. Unlike worksheet functions, a VBA function with
no argument doesn't require an empty set of parentheses. In fact, if you provide an empty set of
parentheses, the VBE will remove them.
To get the system date and time, use the Now function instead of the Date function. Or to get only the
time, use the Time function.
Finding a string length
The following procedure uses the VBA Len function, which returns the length of a string. The Len
function takes one argument: the string. When you execute this procedure, the message box displays 11
because the argument has 11 characters.
Sub GetLength()
Dim MyString As String
Dim StringLength As Integer
MyString = "Hello World"
StringLength = Len(MyString)
MsgBox StringLength
End Sub
Excel also has a function, which you can use in your worksheet formulas. The Excel version and the
VBA function work the same.
Displaying the integer part of a number
The following procedure uses the Fix function, which returns the integer portion of a value — the value
without any decimal digits:
Sub GetIntegerPart()
Dim MyValue As Double
Dim IntValue As Integer
MyValue = 123.456
IntValue = Fix(MyValue)
MsgBox IntValue
End Sub
In this case, the message box displays 123.
VBA has a similar function called Int. The difference between Int and Fix is how each deals with negative
numbers.

• Int returns the first negative integer that's less than or equal to the argument.
• Fix returns the first negative integer that's greater than or equal to the argument.
Determining a file size
The following Sub procedure displays the size, in bytes, of the Excel executable file. It finds this value by
using the FileLen function.
Sub GetFileSize()
Dim TheFile As String
TheFile = "c:\MSOFFICE\EXCEL\EXCEL.EXE"
MsgBox FileLen(TheFile)
End Sub
Notice that this routine hard codes the filename (that is, it explicitly states the path). Generally, this isn't a
good idea. The file might not be on the C drive, or the Excel folder may have a different name. The
following statement shows a better approach:
TheFile = Application.Path & "\EXCEL.EXE"
Path is a property of the Application object. It simply returns the name of the folder in which the
application (that is, Excel) is installed (without a trailing backslash).
Identifying the type of a selected object
The following procedure uses the TypeName function, which returns the type of the selected object (as a
string):
Sub ShowSelectionType()
Dim SelType As String
SelType = TypeName(Selection)
MsgBox SelType
End Sub
This could be a Range, a ChartObject, a TextBox, or any other type of object that can be selected.
The TypeName function is very versatile. You can also use this function to determine the data type of a
variable.

VBA functions that do more than return a value


A few VBA functions go above and beyond the call of duty. Rather than simply return a value, these
functions have some useful side effects. Table 1 lists them.
Table 1: Functions with Useful Side Benefits

Function What It Does

MsgBox Displays a handy dialog box containing a message and buttons. The function returns a
code that identifies which button the user clicks.

InputBox Displays a simple dialog box that asks the user for some input. The function returns
whatever the user enters into the dialog box.

Shell Executes another program. The function returns the task ID (a unique identifier) of the
other program (or an error if the function can't start the other program).

Discovering VBA functions


How do you find out which functions VBA provides? Good question. The best source is the Excel Visual
Basic Help system. Table 2 contains a partial list of functions (minus some of the more specialized or
obscure functions).
For complete details on a particular function, type the function name into a VBA module, move the
cursor anywhere in the text, and press F1.

Table 2: VBA's Most Useful Built-in Functions

Function What It Does

Abs Returns a number's absolute value

Array Returns a variant containing an array


Asc Converts the first character of a string to its ASCII value

Atn Returns the arctangent of a number

Choose Returns a value from a list of items

Chr Converts an ANSI value to a string

Cos Returns a number's cosine

CurDir Returns the current path

Date Returns the current system date

DateAdd Returns a date to which a specified time interval has been

added — for example, one month from a particular date

DateDiff Returns an integer showing the number of specified time intervals between two dates,
for example the number of months between now and your birthday

DatePart Returns an integer containing the specified part of a given

date — for example, a date's day of the year

DateSerial Converts a date to a serial number

DateValue Converts a string to a date

Day Returns the day of the month from a date value

Dir Returns the name of a file or directory that matches a pattern

Erl Returns the line number that caused an error

Err Returns the error number of an error condition

Error Returns the error message that corresponds to an error number

Exp Returns the base of the natural logarithm (e) raised to a power

FileLen Returns the number of bytes in a file


Fix Returns a number's integer portion

Format Displays an expression in a particular format

GetSetting Returns a value from the Windows registry

Hex Converts from decimal to hexadecimal

Hour Returns the hours portion of a time

InputBox Displays a box to prompt a user for input

InStr Returns the position of a string within another string

Int Returns the integer portion of a number

IPmt Returns the interest payment for an annuity or loan

IsArray Returns True if a variable is an array

IsDate Returns True if an expression 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 no valid data

IsNumeric Returns True if an expression can be evaluated as a number

IsObject Returns True if an expression references an OLE Automation object

LBound Returns the smallest subscript for a dimension of an array

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


Log Returns the natural logarithm of a number to base e

LTrim Returns a copy of a string, with any leading spaces removed

Mid Returns a specified number of characters from a string

Minute Returns the minutes portion of a time value

Month Returns the month from a date value

MsgBox Displays a message box and (optionally) returns a value

Now Returns the current system date and time

RGB Returns a numeric RGB value representing a color

Right Returns a specified number of characters from the right of a string

Rnd Returns a random number between 0 and 1

RTrim Returns a copy of a string, with any trailing spaces removed

Second Returns the seconds portion of a time value

Sgn Returns an integer that indicates a number's sign

Shell Runs an executable program

Sin Returns a number's sine

Space Returns a string with a specified number of spaces

Sqr Returns a number's square root

Str Returns a string representation of a number

StrComp Returns a value indicating the result of a string comparison

String Returns a repeating character or string

Tan Returns a number's tangent


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 or trailing spaces

TypeName Returns a string that describes a variable's data type

UBound Returns the largest available subscript for an array's dimension

UCase Converts a string to uppercase

Val Returns the numbers contained in a string

VarType Returns a value indicating a variable's subtype

Weekday Returns a number representing a day of the week

Year Returns the year from a date value

Related

Visual Basic .NET Data Types


Visual Basic.NET All-in-One Desk Reference For Dummies Cheat Sheet
Common VBA Functions
Finding More Power in Visual Studio
Keyboard Shortcut Keys for Visual Studio in Visual Basic 2008
Visual Basic's Role in the Framework
VBA Keyboard Shortcuts
Visual Studio 2010 All-in-One For Dummies Cheat Sheet
Visual Studio 2010 Technology and Terminology
Shortcut Keys to Debug Code in VBA 2007

Login
Add New Comment

Type your comment here.

Showing 18 comments

Watto

Lindacross2010 If you are using ecel and want the format of the column to be 4 digits you can go to format cell and
choose custom, type 0000 as the format and all numbers in that cell will be 4 digits. ie 20 would be displayed as
0020.

3 weeks ago Like Reply

Lindaross2010

Hello, I need help. I have a column of numbers, some are 3 digit numbers and some are 4. I need to add a 0 to the
3 digit numbers. I need Excel vba code to do this. Thanks

1 month ago Like Reply

donna adams

Can someone give me a vba for a form: i am setting up a form so


that when the person clicks on a day of the week they can enter
their name. the form is to be used as a booking with the name and
date and time. if there is anyone who could help please give me a
call at 706-814-1893 or just email me
donna@bradleytaxservice.com.thanks in advance

4 months ago Like Reply

ingeseecrarne

If youÂ’re buying quality health supplement to use in


your health regimen, you might take a look at the Pro Slim Action
Diet. A lot of people wonder wondering why their best Celebrities
look so appealing, hot, and healthy day in, day out. Searching an
all-natural and safe fat reduction formula but so far are actually
struggle to be successful? Don't need to worry because this is the
perfect solution called Pro Slim Diet. This amazing dietary product
is the modern buzz within the health industry. Fortunately that if
you wish to buy this supplement then no longer pen or paper
formalities; you only order it looking at the promotional website.
The thing with regards to the method is that it is mix of
completely 100 % natural ingredients. Folks don't have trust in
modern diets simply because types of diets often cause some
effects. However, if you squeeze in a wholesome dietary supplement
on your diet plan it surely offers you visible results. Using Pro
Slim Diet, you do not only reduce unwanted pounds but will also get
elevated levels of energy. Health specialists claim that this
losing weight method is just like a sweet cherry around the yummy
cake the huge reason this supplement is selling like hot cakes on
the market. Producer of the Pro Slim Action Diet is offering a
risk-free trial version in their product to anyone serious about
losing weight and improving their. Go to Pro Slim Action Diet
homepage below to acquire having access to your special trial
today. great href="http://www.flixya.com/blog/3823494/Pro-Slim-Diet-What-Is-This">
Pro Slim

4 months ago 1 Like Like Reply

James

Interlace the contents of the two text boxes. For example, if I


enter 1234567 in the textbox1 and abcde into textbox2, then I would
expect to see 1a2b3c4d5e6 7" in the listbox. Notice the blank space
after the"6" in the result: the rule I am following is the length
of the contents of the text boxes are not equal then I add blank
spaces to the end of the shorter string to make it of equal length
to the longer string.

4 months ago 1 Like Like Reply

Mike

Mike, Use the record macro function on solver, then format it as


its own sub routine and call the subroutine in another loop.
Cheers, Jackson

6 months ago Like Reply

Mike

Hi, does anyone know how to make the VBA code repeat itself? For
example: I recorded a macro that uses the solver (in excel) and I
would like to apply the macro on multiple optimization problems
with the same constraints over and over again. The macro I recorded
will only apply the solver on those cells specified in the code.
Thanks

8 months ago Like Reply

Brian

i need to create a formula that will add 365 cells located every
other row apart.

9 months ago Like Reply

Alain

Please can anyone inform me about how can I find anything related
to VBA in ArcGIS, such as tutorial or code?? Thank you. Regards

11 months ago Like Reply

husna

i would like to write vba function to compute a histogram in Excel


worksheet. i already write a code for bin(class of interval), but i
have a difficulties to build a code for frequency of my histogram.
can anyone help me by a giving a little bit explanation since i'm
not really good in VBA. what is the function should i use? thanx
for sharing knowledge.

1 year ago Like Reply

husna

i would like to write vba function to compute a histogram in Excel


worksheet. i already write a code for bin(class of interval), but i
have a difficulties to build a code for frequency of my histogram.
can anyone help me by a giving a little bit explanation since i'm
not really good in VBA. what is the function should i use? thanx
for sharing knowledge.

1 year ago 1 Like Like Reply

Claes

I would to write a VBA function, which needs a lot of constants,


some 40. I will put these constant into an array. But how do I get
the constants into the array? Is there a READ function or something
similar? If so, can I use this at the loading of the Excel workbook
so that it is done for the computing session or do I have to use it
at every call of the function?

1 year ago Like Reply

David Harriman

I have a calendar which consists of 365 rows plus twelve for the
months. One column contains the dates and the adjacent column the
days. I use this to enter birthdays, anniversaries, appointments,
meetings, games, etc. I enter this info in the next two or three
columns in the day and date row. I have a cell with the week number
WN in it, and wanted a macro that would look at WN and go to the
week that corresponds with it. I've done this for twenty years
easily in Lotus or Quatropro, with a list of IFs and GoTos. I can't
do it in VB. Got any ideas?

2 years ago Like Reply

uma

why vba.int(1198467) returns 1198466

2 years ago Like Reply

4ndyman

Cassie,

You can't format the string itself, but you can format it after
you place it. For example:

Title = "CO2"

ActiveCell.Value = Title

ActiveCell.Characters(3,1).Font.Subscript = True

If you need to use CO2 a lot, and in different places each time
you use it, you could use the InStr method to find which character
needs to be subscript. In this case,

Dim myTitle as String, myMonth as string

...

myTitle = myMonth & "CO2 Emissions"

With Sheets(myMonth).Range("A1")

.Value = myTitle

.Characters(InStr(myTitle,"CO2") +
2,1).Font.Subscript=True

End With

In this case, the InStr function will return the position of the
"C", so you need to add 2 to it to get to the 2 that you want to
subscript.

(I sure hope I got all my HTML tags in line.)

2 years ago Like Reply

DC

Ron - you can do that by coding an input box where you want the
code to pause and ask for input. This may not be the "correct" way,
but one option is: activecell.value = InputBox("Enter Data")

2 years ago Like Reply

Cassie

How do you format a string variable with part of it in subscript?


Dim Title As String Title = "CO2 Emissions" How do you make the 2
subscript?

2 years ago Like Reply

Ron Van Voorhis


How do I pause a macro to enter data (a number) & have it Sort by newest first

recorded in the ActiveCell, then continue the macro?

2 years ago Like Reply

M Subscribe by email S RSS

Like

blog comments powered by DISQUS

Copyright © 2012 & Trademark by John Wiley & Sons, Inc. All rights reserved.

You might also like