| |
Visual Basic Functions for Excel
VBA comes with many
built-in functions – including String functions, Data Type
Conversion function, Logical functions, Information functions, Numeric /
Mathematical functions, Date & Time functions, File/Directory functions
and Financial functions. A Function is a type of procedure and it
differs from subroutine in that a function always returns a value. Some
functions don’t take argument (eg. Rnd function). How do you use a
function? You can call it (or invoke it) from a subprocedure or
from another function. You can also assign the result of a function to a
variable.
Lookup / Reference Functions
Choose
Switch
Return To Top
Functions to
convert data from one type to another
Example below outlines the syntax of the Data Conversion functions.
CBool(number) |
Boolean (True or False) |
CByte(expression) |
Byte (0 to 255) |
CCur(expression) |
Currency (-922,337,203,685,477.5808 to 922,337,203,685,477.5807) |
CDate(expression) |
Date (Any valid date expression) |
CDbl(expression) |
Double (-1.79769313486232E308 to 1.79769313486232E308) |
CInt(expression) |
Integer (-32,768 to 32,767) |
CLng(expression) |
Long (-2,147,483,648 to 2,147,483,647) |
CSng(expression) |
Single (-3.402823E38 to -1.401298E-45 and 1.401298E-45 to
3.402823E38) |
CStr(expression) |
String (Variable-length strings from 0 to approximately 2
billion characters) |
CVar(expression) |
Variant |
CBool Function
‘ CBool(1+1=3) would return false. The variable x would now contain the
value False.
Dim x as Boolean
x = CBool(1+1=3)
CByte
Function
‘
CBool convert Byte Data Type. Whole Number from 0 to 255
Dim x As Double
x = 138.88
Range("A1:B2") = CByte(x)
CCur
Function
' crVal variable will return value of 123.4568. Cell B1 will return
$123.46 in currency
Dim x As Double, crVal As Currency
x = 123.456789
crVal = CCur(x)
Range("B1") = crVal
CDate
Function
' The variable x will contain the value of 1/1/2008
Dim myDate As String
Dim x As Date
myDate = "13 Jan, 2005"
x = CDate(myDate)
CDbl
function
’ The variable Dble will now contain the value of 0.0052352
Dim Dble As Double
Dble = CDbl(8.18 * 0.008 * 0.08)
CInt
function
’ The 0.0052352 will round up only if the fraction is greater than .5.
eg. CInt(4.50001 will give integer 5)
Dim x As Integer
x = CInt(4.44449)
CLng
function
’ The result will round up only if the fraction is greater than .5. eg.
CLng(23450.5.50001 will give 23451)
Dim x As Long
x = CLng(23450.5)
CSng
function
‘ The variable x would now contain value 1.123457
Dim x As Single
x = CSng(1.123456789)
CStr
function
‘ Variable x would now contain string value of "5” as CStr function
converts a value to a string
Dim x As String
x = CStr(5)
CVar
function
‘ Variable x would now contain variant value of "5” as CVar function
converts a value to a variant
Dim x As Variant
x = CVar(5)
Return To Top
Functions to manipulate
Strings
String
functions without the $ sign take a variant, and these are fine if
you're processing variants as in the case of database programming, where
your input may contain Null values. However, if you're only dealing with
strings, it is more efficient to use the string functions with the
dollar sign ($), eg Chr$().
Asc function
’
Asc function returns a character code, and here Asc(“A”) returns 65
Dim x As Integer
x = Asc("A")
Chr,
ChrB and ChrW functions
' Chr unction is the inverse of the Asc. It returns a string
containing the character associated with the specified character code.
' ChrB is used with byte data
contained in a String. ChrW returns a String
containing the Unicode character.
’ 65
and 66 are the numbers used to retrieve the character A and B, separate
by carriage return/line feed
Dim x As String
x = Chr(65) + Chr(13) & vbLf & Chr(66)
Below table outlines the commonly
used character codes and character constants.
|
Code |
Built-In Constants |
Characters |
Chr(8) |
|
Backspace |
Chr(9) |
vbTab |
Tab |
Chr(10) |
vbLf |
Line-feed |
Chr(11) |
vbVerticalTab |
Shift+Enter |
Chr(12) |
vbFormFeed |
Page Break |
Chr(13) |
vbCr |
Carriage return |
Chr(13)+Chr(10) |
vbCrLf |
Carriage return and Line-feed
combined |
Chr(14) |
|
[Column Break] |
Chr(15) |
|
[Shift In] |
Chr(34) |
— |
Double straight quotation mark |
Chr(39) |
— |
Single straight quote mark |
Chr(40) |
— |
Display as “(” |
Chr(41) |
— |
Display as “)” |
Chr(45) |
— |
hyphen |
Chr(46) |
— |
full stop |
Chr(130) |
— |
Coma |
Chr(145) |
— |
Opening single straight
quotation mark |
Chr(146) |
— |
Closing single straight
quotation mark |
Chr(147) |
— |
Opening double smart quotation
mark |
Chr(148) |
— |
Closing double smart quotation
mark |
Chr(149) |
— |
Bullet |
Chr(150) |
— |
Display as “–“ |
Chr(151) |
— |
Display as “—“ |
Chr(160) |
— |
One space |
ChrW(169) |
— |
? |
ChrW(9650) |
— |
▲ |
ChrW(9660) |
— |
▼ |
ChrW(9658) |
— |
► |
ChrW(9668) |
— |
◄ |
ChrW(9786) |
— |
☺ |
ChrW(9787) |
— |
☻ |
ChrW(9788) |
— |
☼ |
Note that function Chr() is limited from 0-255. For
unicode (hex value) symbols like the copyright symbol, up and down
arrows, left and right arrows, smiling face and so on (?▲▼►◄☺) you have
to use function ChrW() which is able to return a unicode character.
Unicode allows a number range from 0-65,000. Go to start ->All programs
-> Accessories ->system tools ->character map, you can see which symbols
are available in the font (character set).
Or
simply try out this little code:
Dim i As Long
Sheets.Add
For i = 1 To 65000
Cells(i, 2).Value = ChrW(i)
Cells(i, 3).Value = "ChrW(" & i & ")"
Next i
Return To Top
This table shows all the Excel characters as seen in
windows-1252 (US).
|
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
A |
B |
C |
D |
E |
F |
2 |
32 |
!
33 |
"
34 |
#
35 |
$
36 |
%
37 |
&
38 |
'
39 |
(
40 |
)
41 |
*
42 |
+
43 |
,
44 |
-
45 |
.
46 |
/
47 |
3 |
0
48 |
1
49 |
2
50 |
3
51 |
4
52 |
5
53 |
6
54 |
7
55 |
8
56 |
9
57 |
:
58 |
;
59 |
<
60 |
=
61 |
>
62 |
?
63 |
4 |
@
64 |
A
65 |
B
66 |
C
67 |
D
68 |
E
69 |
F
70 |
G
71 |
H
72 |
I
73 |
J
74 |
K
75 |
L
76 |
M
77 |
N
78 |
O
79 |
5 |
P
80 |
Q
81 |
R
82 |
S
83 |
T
84 |
U
85 |
V
86 |
W
87 |
X
88 |
Y
89 |
Z
90 |
[
91 |
\
92 |
]
93 |
^
94 |
_
95 |
6 |
`
96 |
a
97 |
b
98 |
c
99 |
d
100 |
e
101 |
f
102 |
g
103 |
h
104 |
i
105 |
j
106 |
k
107 |
l
108 |
m
109 |
n
110 |
o
111 |
7 |
p
112 |
q
113 |
r
114 |
s
115 |
t
116 |
u
117 |
v
118 |
w
119 |
x
120 |
y
121 |
z
122 |
{
123 |
|
124 |
}
125 |
~
126 |
DEL
127 |
8 |
€
128 |

129 |
‚
130 |
ƒ
131 |
„
132 |
…
133 |
†
134 |
‡
135 |
ˆ
136 |
‰
137 |
Š
138 |
‹
139 |
Œ
140 |

141 |
Ž
142 |

143 |
9 |

144 |
‘
145 |
’
146 |
“
147 |
”
148 |
•
149 |
–
150 |
—
151 |
˜
152 |
™
153 |
š
154 |
›
155 |
œ
156 |
?
157 |
ž
158 |
Ÿ
159 |
A |
160 |
?
161 |
?
162 |
?
163 |
?
164 |
?
165 |
?
166 |
?
167 |
?
168 |
?
169 |
?
170 |
?
171 |
?
172 |
?
173 |
?
174 |
?
175 |
B |
?
176 |
?
177 |
?
178 |
?
179 |
?
180 |
?
181 |
?
182 |
?
183 |
?
184 |
?
185 |
?
186 |
?
187 |
?
188 |
?
189 |
?
190 |
?
191 |
C |
?
192 |
?
193 |
?
194 |
?
195 |
?
196 |
?
197 |
?
198 |
?
199 |
?
200 |
?
201 |
?
202 |
?
203 |
?
204 |
?
205 |
?
206 |
?
207 |
D |
?
208 |
?
209 |
?
210 |
?
211 |
?
212 |
?
213 |
?
214 |
?
215 |
?
216 |
?
217 |
?
218 |
?
219 |
?
220 |
?
221 |
?
222 |
?
223 |
E |
?
224 |
?
225 |
?
226 |
?
227 |
?
228 |
?
229 |
?
230 |
?
231 |
?
232 |
?
233 |
?
234 |
?
235 |
?
236 |
?
237 |
?
238 |
?
239 |
F |
?
240 |
?
241 |
?
242 |
?
243 |
?
244 |
?
245 |
?
246 |
?
247 |
?
248 |
?
249 |
?
250 |
?
251 |
?
252 |
?
253 |
?
254 |
?
255 |
Return To Top
InStr function
‘ It
returns the position of the first occurrence of a string, and the syntax
is InStr( [start], string_being searched, string2, [compare] ). start is
the starting position for the search, is optional, and if it is omitted,
the search will begin at position 1. string_being_searched is the string
that will be searched. string2 is the string to search for. compare is
optional (0=vbBinaryCompare, 1=vbTextCompare), Default is 0. The
variable x would now have a value of 3
Dim x As Integer
x = InStr(1, "today is a nice day", "day")
Str
function
‘ It converts a value to a string.
Dim s As Integer, NumMonths As String
s = InputBox("Enter the number of months you have been learning VBA:",
"")
NumMonths = "You have been learning VBA for already " & s & " months"
MsgBox NumMonths
StrReverse function
' Reverse the character order of a specified
string, which would now become “yad ecin a si yadot”
x = StrReverse$("today
is a nice day")
StrConv function
‘ StrConv function
returns a string converted as specified.
Parameter |
Value |
Description |
vbUpperCase |
1 |
Converts
the string to all uppercase |
vbLowerCase |
2 |
Converts
the string to all lowercase |
vbProperCase |
3 |
Converts
only the first letter to every word to uppercase. |
vbUnicode |
64 |
Converts the string to Unicode. |
vbFromUnicode |
128 |
Converts the string from Unicode to the default
code page of the system. |
StrConv("today is a nice day", 1)
‘
would return "TODAY IS A NICE DAY"
StrConv("today is a nice day", 2)
‘
would return " today is a nice day"
StrConv("today is a nice day", 3)
‘
would return "Today is A Nice Day"
Return To Top
StrComp
function
‘ Returns a Variant (Integer) indicating the result of comparing string1
and string2. The syntax is:
StrComp(string1, string2[,compare])
The
compare argument is optional, specifying the textual comparison
vbTextCompare or vbBinaryCompare. If the compare
argument
is
Null,
an error occurs. If compare is omitted, the Option Compare setting
determines the type of comparison.
The compare argument settings are:
Constant |
Value |
Description |
vbUseCompareOption |
-1 |
Performs a comparison using the setting of the Option Compare
statement. |
vbBinaryCompare |
0 |
Performs a binary comparison. |
vbTextCompare |
1 |
Performs a textual comparison. |
vbDatabaseCompare |
2 |
Performs a comparison based on information in your database. |
The
StrComp function has the following return values:
Condition if : |
StrComp returns: |
string1 is less than string2 |
-1 |
string1 is equal to string2 |
0 |
string1 is greater than string2 |
1 |
string1 or string2 is Null |
Null |
‘ In
the example below, if the compare argument is 1, a textual comparison is
performed; if the compare argument is 0 or omitted, a binary comparison
is performed
Dim Str1, Str2, MyCompare
Str1 = "AMAT": Str2 = "amat"
'
define variables
MyCompare = StrComp(Str1, Str2, 1)
'
returns 0
MyCompare = StrComp(Str1, Str2, 0)
'
returns -1
MyCompare = StrComp(Str2, Str1)
'
returns 1
Return To Top
Format
function with Strings
Format function returns the expression as a formatted string, and the
syntax is Format (expression,[format]).
Expression is the
value to format and it is optional
Format |
Explanation: |
General Number |
Displays a number without thousand separators |
Currency |
Displays thousand separators as well as two decimal places |
Fixed |
Displays at least one digit to the left and two digits to the
right of the decimal place |
Standard |
Displays the thousand separators, at least one digit to the left
and two digits to the right of decimal place" |
Percent |
Displays a percent value - that is, a number multiplied by 100
with a percent sign" |
Scientific |
Scientific notation |
Yes/No |
Displays No if the number is 0. Displays Yes if the number is
not 0 |
True/False |
Displays True if the number is not 0. Displays False if the
number is 0 |
On/Off |
Displays Off if the number is 0. Displays On is the number is
not 0 |
General Date |
Displays date based on your system settings |
Long Date |
Displays date based on your system's long date setting |
Medium Date |
Displays date based on your system's medium date setting |
Short Date |
Displays date based on your system's short date setting |
Long Time |
Displays time based on your system's long time setting |
Medium Time |
Displays time based on your system's medium time setting |
Short Time |
Displays time based on your system's short time setting |
Format("1,234.56", "General Number")
'
return 1234.56
Format("123.4", "#,##0.00")
'
return 123.40
Format("000.1234", "#,###.000")
'
return 0.123
Format("13.4", "#,0#0.00")
'
return 013.40
Format("1234567", "$0,000.0")
'
return $1,234,567.0
Format("123.4", "Standard")
'
return 123.40
Format("0.785", "Percent")
‘
return 78.50%
Format("0.00001", "Yes/No")
‘
return Yes
Format("0.00001", "True/False")
‘
return True
Format("0.00001", "On/Off")
‘
return On
Format("1235.6", "Currency")
'
return $1,234.50
Format("Jan 9, 2008", "General Date")
'
return 1/9/2008
Format("Jan 9, 2008", "Short Date")
'
return 9/1/2008
Format("23.59:59", "long time")
'
return 11:59:59 PM
Format("23.59:59", "short time")
'
return 23:59
Format("11.59:59 PM", "short time")
'
return 23:59 PM
Format(#12/3/2006#, "d")
'
display as date "3" without a leading zero
Format(#12/3/2006#, "dd")
' display as "3" with a leading zero
Format(#12/3/2006#, "ddd")
'
display the date of "3" as the day "Sun"
Format(#12/3/2006#, "dddd")
' display date of "3" as full name "Sunday"
Format(#12/3/2006#, "ddddd")
'
display complete date in short date format as "12/3/2006"
Format(#12/3/2006#, "dddddd")
' display complete date as "Sunday, December 03, 2006"
Format(#12/3/2006#, "w")
' display as integer "1", ie. from
1(Sunday) to 7(Monday)
Format(#12/3/2006#, "ww")
' display as integer from number week "49" in year 2006
Format(#1/3/2006#, "m")
' display 1 as number of the month Jan without leading zero
Format(#1/3/2006#, "mm")
' display 01 as number of the month Feb with leading zero
Format(#1/3/2006#, "mmm")
' display month in a 3-letters abbreviation as "Jan"
Format(#1/3/2006#, "q")
' display as quarter "1" of the year 2006
Format(#12/3/2006#, "y")
' display as day "337" of the year 2006
Format(#12/3/2006#, "yy")
'
display a two-digit year as "06"
Format(#11:59:58 AM#, "hh")
'
display a two-digit hour as "23"
Format(#11:59:58 AM#, "nn")
'
display a two-digit minute as "59"
Format(#11:59:58 AM#, "ss")
' display a two-digit second as "58"
Format(#11:59:00 AM#, "AM/PM")
' display AM in a 12-hour clock
Return To Top
' This will display "12/3/2006 11:59:58 PM" as full date and full time
in the system's default time format
Format(#12/3/2006 11:59:58 PM#, "ddddd ttttt")
FormatNumber
'
It returns
an expression formatted as a number. The syntax is:
FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers
[,GroupDigits]]]])
NumDigitsAfterDecimal,
IncludeLeadingDigit, UseParensForNegativeNumbers and GroupDigits are all
optional.
For FormatNumber and FormatCurrency functions, the
IncludeLeadingDigit, UseParensForNegativeNumbers, and
GroupDigits arguments have the following settings:
Constant |
Value |
Description |
vbTrue |
1 |
True |
vbFalse |
0 |
False |
vbUseDefault |
2 |
Use the setting from the computer's
regional settings. |
MsgBox FormatNumber("123",
3, vbFalse, vbFalse, vbUseDefault)
‘
return 1,23.000
FormatCurrency
The
syntax is:
FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]])
Debug.Print FormatCurrency("123.456", , vbFalse, vbUseDefault)
'
return $123.46
Debug.Print FormatCurrency(1234.5678, , vbUseDefault)
'
return $1,234.57
Debug.Print FormatCurrency(1234.5678, , vbFalse)
'
return $1,234.57
Debug.Print FormatCurrency(1234.5678, 0)
' return $1,235
FormatDateTime
' returns an expression formatted as a date or time. The syntax is:
FormatDateTime(Date[,NamedFormat])
The NamedFormat argument has the following settings:
Constant |
Value |
Description |
vbGeneralDate |
0 |
Display a date and/or time. If there
is a date part, display it as a short date. If there is a time
part, display it as a long time. If present, both parts are
displayed. |
vbLongDate |
1 |
Display a date using the long date
format specified in your computer's regional settings. |
vbShortDate |
2 |
Display a date using the short date
format specified in your computer's regional settings. |
vbLongTime |
3 |
Display a time using the time format
specified in your computer's regional settings. |
vbShortTime |
4 |
Display a time using the 24-hour
format (hh:mm). |
MsgBox FormatDateTime(#12/13/2006#,
vbGeneralDate)
‘
returns 12/13/2006
MsgBox FormatDateTime(#12/13/2006#,
vbLongDate)
‘
returns
Wednesday, December 13, 2006
MsgBox FormatDateTime("08:45", vbShortTime)
‘
returns 08:45
MsgBox FormatDateTime("08:45", vbLongTime)
'
returns
8:45:00 AM
Return To Top
LCase function
and UCase function
LCase("VB Express
2005")
‘ returns "vb express 2005"
UCase("VB Express 2005")
‘ returns "VB EXPRESS 2005"
LCase("VB Express 2005")
‘
returns "vb express 2005"
UCase("VB Express 2005")
‘
returns "VB EXPRESS 2005"
Concatenate function
(with & Operator)
x = "Aero" & "Smith"
‘
return “AeroSmith”
Join
' returns a string created by joining a number of substrings
contained in an array. The syntax is: Join(sourcearray[, delimiter]).
sourcearray - One-dimensional array containing substrings to be
joined. delimiter - Optional. String character used to separate the
substrings in the returned string.
Dim Arr(3) As String, strJoin As String
Arr(0) = "www"
Arr(1) = "amat"
Arr(2) = "com"
strJoin = Join(Arr, ".")
strJoin = Left(strJoin,
Len(strJoin)
- 1)
Debug.Print
strJoin
'
returns www.amat.com
L en
function
’
Display 20 as length of the specified string
Cells(1, 1) = "website www.amat.com"
x = Cells(1, 1)
Cells(1, 1).Offset(0, 1) = Len(x)
Return To Top
Left
function
’
Extract a 4 characters substring “webs” from a specified string,
starting from the left-most character
x = Left("website www.amat.com", 4)
MsgBox "Left(""website www.amat.com"", 4)" & vbCr & vbCrLf & "returns
""" & x & """"
Right
function
’
Extract a 8 characters substring “amat.com” from a specified string,
starting from the right-most character.
Right("website www.amat.com", 8)
Mid
function
‘ It
returns a substring of 4 characters length starting from position 7,
which is “soft”. In the second example, Mid is used on the left side of
an assignment statement, where it replaces a substring within a string.
The syntax is Mid(string, start[, length])
t = “Microsoft”
x = Mid(t, 6, 4) ‘
returns “soft”
y = Mid(t, 1, 5) = "Compu"
‘
replaces “Micro” with “Compu”
' In
this second example, the Do Until…Loop run backward through the
specified string, and stops until it reaches the first letter ‘e’. It
then store the position of the found character in the integer variable i.
The message box displays that resulting sub-string one character to the
right of “e” (subtracting 14 and subtracting 1 from the length of string
txt)
Dim txt As String, i As Integer
txt = "website www.amat.com"
i = Len(txt)
Do Until Mid(txt, i, 1) = "e"
i = i - 1
Loop
MsgBox "the website name is " & Right(txt, Len(txt) - i - 1)
Return To Top
Replace
function
‘ It returns a string
in which a specified substring “-“ is replaced with another substring “/”
x =
Replace$("1-1-2007", "-", "/")
RTrim
function
‘
Removes the leading blank spaces from the string
RTrim("Microsoft ")
LTrim
function
‘
Removes the trailing blank spaces from the string
LTrim("Microsoft ")
Trim
function
‘
Removes both leading and trailing blank spaces from a string
Trim(" Microsoft ")
CurDir function
’
Returns the current path
CurDir () ‘
would return "C:\Documents and Settings\user\My Documents"
CurDir ("D") ‘
would return "D:\"
Val
function
'
Val function stops searching once it found first non-numeric character,
which does not include spaces
Dim x As Double
x = Val("123 4 5AB") '
returns 12345
x = Val("8-168, block 960") '
returns 8
x = Val(" 960-Jurong St 91")
'
returns 960
x = Val(" Blk960-Jurong")
'
returns 0
x = Val("091 960") '
returns 91960
Space function
‘ It
inserts one space character in between “Visual” and “Basic”
t = "VisualBasic"
x = Mid(t, 1, 6) & Space(1) & Right(t, 5)
Return To Top
Logical Functions
Select Case
Statements
Case
statement has the functionality of a multiple ELSEIF statements. Use
Select Case when the decision you want to arrive at depends on one
variable or expression (known as text case) that has more different
values that you need to evaluate. The syntax is:
Select Case Test_Expression
Case condition_1
statement_1
Case condition_2
statement_2
...
Case condition_n
statement_n
Case Else
statement_else
End Select
‘
If
you have many different conditions, Elseif become unhandy, use Select
Case instead. In this example, when the specified conditions are met, it
populates the string text one cell to the right
Dim finalRow As Long, n As Long
finalRow = Cells(65536, 1).End(xlUp).Row
For n = 2 To finalRow
Select Case Cells(n, 1).Value
Case "Down"
Cells(n, 1).Offset(, 1).Value = "delivery time is 4 to 5
days"
Case "Priority"
Cells(n, 1).Offset(, 1).Value = "delivery time is 8 to 10
days"
Case "Regular"
Cells(n, 1).Offset(, 1).Value = "delivery time is 14 days"
Case Else
End Select
Next n
Return To Top
IF-THEN-ELSE
function
The
syntax for the IF-THEN-ELSE statement is:
If condition_1 Then
statement_1
ElseIf condition_2 Then
statement_2
ElseIf condition_n Then
statement_n
Else
statement_else
End If
’ An
alternative to the Select Case statement. When the specified conditions
are met, it populates the string text one cell to the right
Dim finalRow As Long, n As Long, r As String
finalRow = Cells(65536, 1).End(xlUp).Row
For n = 2 To finalRow
r = Cells(n, 1).Value
If r = "01" Then
Cells(n, 1).Offset(, 1).Value = "delivery time is 4 to 5
days"
ElseIf r = "02" Then
Cells(n, 1).Offset(, 1).Value = "delivery time is 8 to 10
days"
ElseIf r = "03" Then
Cells(n, 1).Offset(, 1).Value = "delivery time is 14
days"
Else
End If
Next n
’
This example loops through the Used Range in column A, and change the
font color of the Used Range in first 2 columns as soon as a specified
condition is made.
Dim iRow As Long
Dim rng As Range, rCell As Range
Sheets("Sheet1").Select
Set rng = Sheets("Sheet1").Range(Cells(2, "A"), Cells(Rows.Count, "A").End(xlUp))
For Each rCell In Range(Cells(1, "A"), Cells(Rows.Count, "A").End(xlUp))
If Not rng.Find(what:="01", LookIn:=xlValues, LookAt:=xlWhole) Is
Nothing Then
rCell.Resize(1, 2).Font.ColorIndex = 3
ElseIf Not rng.Find(what:="02", LookIn:=xlValues, LookAt:=xlWhole)
Is Nothing Then
rCell.Resize(1, 2).Font.ColorIndex = 5
ElseIf Not rng.Find(what:="03", LookIn:=xlValues, LookAt:=xlWhole)
Is Nothing Then
rCell.Resize(1, 2).Font.ColorIndex = 7
Else
rCell.Resize(1, 2).Font.ColorIndex = 10
End If
Next
’
If
it finds any errors in the 1st sheet, it fills the cell background of
the cells that have errors with red color, or else it displays a message
to say that it finds no error. You need to always enable error handling
so that a run-time error will not occur if the SpecialCells method
doesn’t find any special cells. When SpecialCells give error, the Range
variable rngSpecial will not be initialized. Using Not…Is Nothing
method, you can see the action result when there are errors found
in cells. Finally, set the variable names to Nothing dissociated
the specified variables from the objects to which they are referred. It
means that the variable now refers to nothing, but the variable name
still exists in memory.
Dim ws As Worksheet, rngSpecial As Range, rngCell As Range
On Error Resume Next
Set ws = ActiveWorkbook.Sheets(1)
Set rngSpecial = ws.Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
If Not rngSpecial Is Nothing Then
rngSpecial.Interior.ColorIndex = 3
Else
MsgBox "found no formula error in " & ws.Name
End If
‘
to dissociate variables from the objects
Set rngSpecial = Nothing
Set rngCell = Nothing
Set ws = Nothing
Note: In the
expression.SpecialCells(Type, Value)
statement, if Type is either xlCellTypeConstants or
xlCellTypeFormulas, this argument is used to determine which
types of cells to include in the result. These values can be added
together to return more than one type as shown in example below. The
default is to select all constants or formulas, no matter what the type.
ActiveSheet.Cells.SpecialCells(xlCellTypeConstants, xlErrors +
xlTextValues)
XlCellType can be one of these XlCellType constants :
xlCellTypeAllFormatConditions |
Cells of any format |
xlCellTypeAllValidation |
Cells having validation criteria |
xlCellTypeBlanks |
Empty cells |
xlCellTypeComments |
Cells containing notes |
xlCellTypeConstants |
Cells containing constants |
xlCellTypeFormulas |
Cells containing formulas |
xlCellTypeLastCell |
The last cell in the used range |
xlCellTypeSameFormatConditions |
Cells having the same format |
xlCellTypeSameValidation |
Cells having the same validation criteria |
xlCellTypeVisible |
All visible cells |
XlSpecialCellsValue can be one of these
XlSpecialCellsValue
constants :
-
xlErrors
xlLogical xlNumbers xlTextValues
Return To Top
Information
Functions
IsNothing
function
’
IsNothing function determines if an object variable is associated with
any object instance
Dim var As Object '
No instance assigned to this variable yet
Dim x As Boolean
x = IsNothing(var)
'
Returns True
var = "XYZ"
x = IsNothing(var)
'
Returns False
var = Nothing '
Disassociate the variable from any instance
x = IsNothing(var)
'
Returns True
IsEmpty
function
‘ IsEmpty function determines whether a variable has been initialized. It
returns True if the variable is
uninitialized, or is
explicitly set to Empty
Dim var, x
x = IsEmpty(var) '
Returns True
var = Null '
Assign Null
x = IsEmpty(var) '
Returns False
var = Empty '
Assign Empty
x = IsEmpty(var) '
Returns True
Return To Top
IsNull function
'
IsNull function determines whether a variable contains a Null. It
returns True if expression is Null; otherwise, IsNull returns False. The
Null value indicates that the variable contains no valid data. Null is
not the same as Empty, which indicates that a variable has not yet been
initialized. It is also not the same as a zero-length string (""), which
is sometimes referred to as a null string.
Dim var, x x = IsNull(var)
' Returns False
var = Null
' Assign Null x = IsNull(var)
' Returns True var = Empty
' Assign Empty x = IsNull(var)
' Returns False
Return To Top
IsErrorFunction
‘
IsError function is used to determine if a
numeric expression
represents an error. It returns the boolean value depending if the
value is (#N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME? or #NULL!),
unlike the
IsErr()
function which will not identify cells that contain a #N/A as an error.
Dim lastrow As Long, i As Long
lastrow = Range("A65536").End(xlUp).Row
For i = 2 To lastrow
If Application.WorksheetFunction.IsError(Cells(i, 2)) = True Then
Cells(i, 2).Value = ""
End If
Next i
IsNA
’
Value refers to the #N/A (value not available) error value.
IsErr
function refers to any error value except #N/A
Dim lastrow As Long, i As Long, x As Variant
lastrow = Range("A65536").End(xlUp).Row
For i = 2 To lastrow
x = Cells(i, 1)
If Application.WorksheetFunction.IsNA(x) = True Then
Cells(i, 2) = 0
ElseIf Application.WorksheetFunction.IsErr(x) = True Then
Cells(i, 2) = ""
Else
Cells(i, 2) = x
End If
Next i
Return To Top
IsLogical Function
’
Refers to a logical value. The function returns one of the following
strings: Logical, Text, Error, Date, Time, Value, Blank.
Use this function as you would with other Excel functions, example:
=CellType(A2)
Function CellType(Cell)
'
Volatile function must be recalculated whenever calculation occurs in
any cells
Application.Volatile
Select Case True
Case Application.IsLogical(Cell): CellType = "Logical"
Case Application.IsText(Cell): CellType = "Text"
Case Application.IsErr(Cell): CellType = "Error"
Case IsDate(Cell): CellType = "Date"
Case InStr(1, Cell.Text, ":") <> 0: CellType = "Time"
Case IsNumeric(Cell): CellType = "Value"
Case IsEmpty(Cell): CellType = "Blank"
End Select
End Function
IsRef
Function
‘
Returns a Boolean value that indicates whether an expression evaluates
to a reference type. IsReference returns True if Expression represents a
reference type, such as a class instance, a String type, or an array of
any type; otherwise, it returns False. A reference type contains a
pointer to data stored elsewhere in memory. A value type contains its
own data
Public Function IsReference(ByVal Expression As Object) As Boolean
IsRef(MyRange)
‘
returns TRUE if MyRange is defined as a range name
Return To Top
IsText
’
Value refers to text. The code below shows the first cell being found in
Column A that is not formatted as text
lastrow = Range("A65536").End(xlUp).Row
For i = 1 To lastrow
If Application.WorksheetFunction.IsText(Cells(i, 1)) = False Then
Else
MsgBox "Cells A" & i & " in Column A is a non-text format"
Exit Sub
End If
Next i
IsNonText
’
Value refers to any item that is not text. (Note that this function
returns TRUE if value refers to a blank cell.)
If Application.WorksheetFunction.IsNonText(Cells(2, 1)) = True Then
MsgBox "A2 is not formatted as text"
Else
MsgBox "A2 is formatted as text"
End If
IsNumber
function
‘ Function returns True
if the data type of the argument is numeric; otherwise Function returns
False. Specifically, it considers the following data types numeric:
Boolean, Byte, Currency, Date, Double, Integer, Long, and Single.
Public Function IsNumber(ByVal Value
As Variant) As Boolean
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9.]*" And Len(Value) > 0 And Value <>
vbNullString
End Function
IsNumber(12)
‘ returns True if 12
was entered as a number
IsNumber(123.45)
‘ returns True
IsNumber($123.45)
‘ returns True
IsNumber(#1/1/2005#)
‘ returns True
IsNumber("12")
‘ returns False
IsNumber("MJ7")
‘ returns False
Return To Top
IsNumeric function
’
IsNumeric function determines if a variable can be evaluated as a number
var = "123.456"
x = IsNumeric(var)
' returns True
var = "2224 Helpdesk"
x = IsNumeric(var)
'
returns False
’
Run through
column A and only if the Cells are numeric will it copy the Cell value
to the 4 Cells on the right
Dim rTarget As Excel.Range
Dim LastRow As Long, r As Long
LastRow = Cells(65536, 1).End(xlUp).Row
For r = 1 To LastRow
Set rTarget = Cells(r, 1)
If IsNumeric(rTarget) Then
rTarget.Copy Range("B" & r & ":E" & r)
Else
End If
Next
IsDate
function
'
IsDate function determines if an expression can be converted to a date.
Dim c As Range
Set c = Cells(1, 1)
With c
If .Value = "" Or Not IsDate(.Value) Then
MsgBox "you must it enter as date"
.SetFocus
Exit Sub
End If
End With
Note: Focus is the ability to receive mouse clicks or keyboard input at
any one time. SetFocus moves the focus to this instance of
an object. If setting the focus fails, the focus reverts to the previous
object and an error is generated.
Return To Top
IsArray
Function
‘
IsArray returns True if the variable points to an array; otherwise, it
returns False. Following example checks if several variables refer to an
array
Dim firstArray(4), secondArray(3) As Integer
Dim thisString As String
Dim x As Boolean
x = IsArray(firstArray)
'
return True
x = IsArray(secondArray)
'
return True
x = IsArray(thisString)
'
return False
IsMissing
Function
‘ In VB4, VB5, VB6,
IsMissing function was used to test for optional arguments passed to
user-defined function procedures as variants (here X is defined as an
Optional parameter). Default values were not required for optional
arguments; if no value was passed then IsMissing returned True
(IsMissing actually determines if a Variant variable is empty).
Therefore, IsMissing will not work if you define an Optional parameter
of a specific (non-Variant) data type. In Visual Basic .NET, the
IsMissing function has been removed from the language and replaced with
IsNothing, and default values are now required for all optional
arguments
' In Visual Basic 6.0
Function DoThis(Optional X As Variant)
If IsMissing(X) Then
' Do something here...
End If
End Function
Dim X As Object
' Do something with the
object
Set X = Nothing
' IsMissing in the
DoThis function returns false
DoThis(X)
’
An
example of IsMissing function actually determines if a Variant variable
is empty
Private Function SampleFunction(Optional m As Variant)
On Error Resume Next
If IsMissing(m) Then
MsgBox ("Missing m")
Else
MsgBox ("Not Missing m")
End If
End Function
' After upgrade to Visual
Basic .NET
Function DoThis(Optional ByRef X As Object
= Nothing) As Object
' IsMissing function
was changed to IsNothing
If IsNothing(X) Then
' Do something here
End If
End Function
Return To Top
Lookup / Reference
Functions
Choose function
‘
Choose function returns a value from a list of values based on a given
position. The syntax is:
Choose(index position, choice1, choice2, ... choice n)
‘
Choose function evaluates an numeric argument and a list. In the
following example, there are four arguments in the list, the numeric
argument should be between 1 to 3. If the numeric argument is 3, Choose
returns the third item in the list. If the numeric argument is less than
one or greater than the number of items in the list, Choose returns
Null. This Select Case statement is cumbersome as compared to using the
Choose function. The second example using Choose function to display a
name in response to an index passed into the procedure in the Choice
parameter.
Public Function ChooseMySelect(Choice As Integer) As String
Dim X As String
Select Case Choice
Case 1
X= "1"
Case 2
X= "2"
Case 3
X= "3"
Case Else
X= vbNullString
End Select
ChooseMySelect = X
End Function
Public Function ChooseMySelect(Choice As Integer) As String
Dim X
X = Choose(Choice, "1", "2", "3)
ChooseMySelect = "" & X
End Function
‘
This following example of initializing with long static arrays is
equally long and cumbersome as compared
to using the more handy Choose function with arrays.
Private Sub UseLongStaticArray()
Dim iArray(1 To 5) As Currency
Dim i As Integer
For i = 1 To 5
iArray(1) = 100
iArray(2) = 500
iArray(3) = 2000
iArray(4) = 5000
iArray(5) = 10000
Cells(i, 1) = iArray(i)
Next
End Sub
Private Sub UseChooseNotStaticArray()
Dim iArray(1 To 5) As Currency
Dim i As Integer
For i = 1 To 5
iArray(i) = Choose(i, 100, 500, 2000, 5000, 10000)
Cells(i, 1) = iArray(i)
Next
End Sub
Return To Top
Switch
function
‘
Evaluates a list of
expressions
and returns a Variant value or an expression associated with the first
expression
in the list that evaluates as True. If expression1 is True, then Switch
returns the value indicated by value1; and
so on. The Syntax is:
Switch(expression1, value1, expression2, value2, ... expression_n,
value_n)
Function LanguageMatch(ByVal ThankYouIn As String) As String
LanguageMatch = Switch(ThankYouIn = "Russian", "spaciba", ThankYouIn
= _
"German", "Danke", ThankYouIn = "Spanish", "
gracias")
End Function
Return To Top
File/Directory
Functions
ChDir
statement
’
ChDir statement allows you to change the current directory or folder on
the current drive as the following example
would do.
ChDir "C:\william91128\GPP_DSM\"
ChDrive
statement
’
It
changes the current directory to the one specified by the path argument
ChDrive "C"
ChDir "C:\ william91128"
Dir
function
’
It
returns a String value containing the name of a file, directory, or
folder that matches a pattern (specified in the pathname argument)
and/or a file attribute (specified in attributes). You can use wildcard
characters to specify multiple files (* allows you to match any string
of any length, including zero length; ? allows you to match on a single
character).
Dir[(pathname[, attributes])]
File
attributes is optional and can be one or a combination of the
following values:
VB Constant |
Value |
Explanation |
vbNormal |
0 |
Normal (Default) |
vbReadOnly |
1 |
Read-only |
vbHidden |
2 |
Hidden |
vbSystem |
4 |
System file |
vbVolume |
8 |
Volume label |
vbDirectory |
16 |
Directory or folder |
vbAlias |
64 |
File name is an alias |
Dim Lpath As String
Lpath = Dir("C:\MyBook?.txt", 1)
If Len(Dir("C:\MyBook?.txt")) > 0 Then
MsgBox "the file does exist"
Else
MsgBox "file does not exist"
End If
Return To Top
FileLen
function
’
In example below, the variable called Lpath would now contain the size
of the file InvTargetFY08.xls in bytes.
Dim Lpath As Long
Lpath = FileLen("C:\william91128\GPP_DSM\InvTargetFY08.xls")
MkDir
statement
’ It
creates the new directory or folder specified by the path argument. The
MkDir statement in the first line will only create the GPP_DSM directory
under C:\william91128 directory. It will not create the C:\william91128
directory itself. However, if you are not sure whether GPP_DSM directory
already exist or not, the second line IF-THEN-ELSE code will do the job.
MkDir "C:\william91128\GPP_DSM"
If Len(Dir("C:\william91128\GPP_DSM", vbDirectory)) = 0 Then
MkDir "C:\william91128\GPP_DSM"
Else
End If
FileDateTime function
’
It
returns the date and time of when a file was created or last modified,
depending on your locale date setting
Dim LastModified As Date
LastModified = FileDateTime("C:\william91128\GPP_DSM\InvTargetFY08.xls")
Cells(1, 1).Value = "Report Last
Modified date was on " & LastModified
Return To Top
GetAttr
function
’
It returns an Integer value that represents the attributes for the file,
directory, or folder
Dim Lpath As Long
Lpath = GetAttr("C:\william91128\GPP_DSM\InvTargetFY08.xls")
MsgBox Lpath
The
GetAttr
will return one or a combination of the following values:
VB Constant |
Value |
Explanation |
vbNormal |
0 |
Normal |
vbReadOnly |
1 |
Read-only |
vbHidden |
2 |
Hidden |
vbSystem |
4 |
System file |
vbDirectory |
16 |
Directory or folder |
vbArchive |
32 |
File has been changed since last backup |
vbAlias |
64 |
File name is an alias |
SetAttr
statement
’
It
sets the attributes of a file. The attributes argument can use several
VB constants (vbNormal, vbReadOnly, vbHidden, vbSystem, vbDirectory, and
vbArchive) that can be combined bitwise to determine which attributes
are set.
SetAttr "c:\ InvTargetFY08.xls", vbReadOnly + vbHidden
Return To Top
Date & Time
Functions
Date
function
‘
Returns a Variant (Date) containing the current system date. In the
example, the variable called MyDate would now contain the current system
date
Dim MyDate
MyDate = Date
DateValue function
‘
It
converts a string to a date or it returns the serial number of a date.
Dim MyDate
MyDate = DateValue("August 19, 1962")
MyDate = DateValue("19-August-1962")
MyDate = DateValue("19,August,1962")
MyDate = #8/19/1962#
‘
can also use date literals # to directly assign a date to a Variant
Dim daysCalc As Long
MyDate = DateValue(Date)
daysCalc = DateValue(Date) - #8/19/1962#
MsgBox "It has been " & daysCalc & " days past since " & #8/19/1962#
TimeValue function
’
This function returns a Variant (Date) containing the time. If the time
argument contains date information, TimeValue doesn't return it.
However, if time includes invalid date information, an error occurs. The
syntax is:
TimeValue(time)
Dim MyTime As Date
MyTime = TimeValue("23:59:58") '
returns ‘11:59:58 PM’
Return To Top
Year
function
’
Returns a Variant (Integer) containing a four-digit year (1900 to 9999)
representing the year given a date value.
In this example, the variable iYear would contain 1962
Dim iDate, iYear
iDate = #8/19/1962#
iYear = Year(iDate)
Month function
'
Returns a Variant (Integer) specifying a whole number between 1 and 12,
representing the month of the year.
The variable m would now contain value of 12.
Dim m As Integer
m = Month(#8/19/1962#)
MsgBox "it is month " & m
Return To Top
Weekday
function
‘
It
returns a number representing the day of the week, given a date value.
The syntax is:
Weekday(date, return_value)
return_value
is optional, which is the option used to display the result. It can be
any of the following values:
Value |
Explanation: |
1 |
Returns a number from 1 (Sunday) to 7 (Saturday). This is the
default if parameter is omitted. |
2 |
Returns a number from 1 (Monday) to 7 (Sunday) |
3 |
Returns a number from 0 (Monday) to 6 (Sunday) |
Dim sArray(1 To 6) As Date, iArray(1 To 6) As String
Dim i As Integer
For i = 1 To 6
sArray(i) = Choose(i, #8/19/1962#, #8/19/1965 11:59:59 PM#, "19 August
1974", _
"1985 August 19", "August,19 2007", 40234)
Cells(i, 1) = sArray(i)
Next
For i = 1 To 6
iArray(1) = "=Weekday(A1)"
iArray(2) = "=Weekday(A2)"
iArray(3) = "=Weekday(A3)"
iArray(4) = "=Weekday(A4)"
iArray(5) = "=Weekday(A5)"
iArray(6) = "=Weekday(A6)"
Cells(i, 2) = iArray(i)
Next
Return To Top
DateAdd
function
'
Returns a date after which a certain time/date interval has been added.
The syntax is:
DateAdd(interval, number, date)
The
interval argument has these settings:
Setting |
Description |
yyyy |
year |
q |
Quarter |
m |
Month |
y |
Day of year |
d |
Day |
w |
Weekday |
ww |
Week |
h |
Hour |
n |
Minute |
s |
Second |
‘
This example adds one month to January 1st
DateAdd("m", 1, "1-Jan-05")
'
Using DateAdd function, this code takes a date from input box and
displays a corresponding date after lapse of a specified number of
interval time, ie. days in this example.
Dim dt As Date
Dim intervalArg As String
Dim iNum As Integer
Dim display
intervalArg = "d"
dt=InputBox("Enter a PO date")
Cells(1, 1) = "PO creation date: " & dt
iNum = InputBox("Enter number of days this PO is overdue")
Cells(2, 1) = "Number of days PO is overdue: " & iNum
display = "As of " & DateAdd(intervalArg, iNum, dt) &
",Open PO is overdue " & iNum & "days"
MsgBox display
Cells(3, 1) = display
Return To Top
DateDiff function
’ Returns a Variant of subtype Long that
represents the difference between two date values. The interval
argument
(refer to the previous example) contains a code that represents the unit
of time, eg. yyyy for years, that will be
returned by the function.firstdayofweek is optional. It is a constant that
specifies the first day of the week. If this parameter is omitted, Excel
assumes that Sunday is the first day of the week. firstweekofyear
is optional. It is a constant that specifies the first
week of the year. If this parameter is omitted, Excel assumes that the
week containing Jan 1st is the first week of
the year.
DateDiff(interval, date1, date2, [firstdayofweek], [firstweekofyear])
Range("A1") = "1 Feb, 2005"
Range("A3") = "14-April 2005"
Range("A5") = #8/31/2005#
Range("A2") = "=DiffTwoDates(A1, A3)" 'B2 would return 72
Range("A4") = "=DiffTwoDates(A3, A5)" 'B4 would return 139
MsgBox "difference in days between A1 and A3 is: " & Range("A2")
MsgBox "difference in days between A3 and A5 is: " & Range("A4")
Return To Top
MonthName function
‘
returns a string representing the month given a number from 1 to 12. The
parameter number is a value from 1 to 12, representing the month.
Parameter abbreviate is optional. If this parameter is set to
TRUE, it means that the month name is abbreviated. If this parameter is
set to FALSE, the month name is not abbreviated.
MonthName(number, [abbreviate ])
MonthName(12, True) ‘
would return Dec
MonthName(12, False) ‘
would return December
WeekdayName function
‘
returns a string representing the day of the week given a number from 1
to 7. The Syntax is:
WeekdayName(weekday, abbreviate, firstdayofweek)
Parameter weekday has a value from 1 to 7. Parameter
abbreviate is optional. If this parameter is set to
TRUE, it means that the weekday name is abbreviated. If this parameter
is set to FALSE, the weekday name is not abbreviated.
firstdayofweek argument is optional. It determines what day is
to be the first day of the week. If this last parameter is omitted, the
Weekday function assumes that the first day of the week is Sunday.
firstdayofweek
argument can have
the following values:
Constant |
Value |
Description |
vbUseSystem |
0 |
Use National Language Support (NLS) API setting |
vbSunday |
1 |
Sunday (default) |
vbMonday |
2 |
Monday |
vbTuesday |
3 |
Tuesday |
vbWednesday |
4 |
Wednesday |
vbThursday |
5 |
Thursday |
vbFriday |
6 |
Friday |
vbSaturday |
7 |
Saturday |
WeekdayName(7, True)
'
would return 'Sat'
WeekdayName(7, True, 4) '
would return 'Tue'
WeekdayName(7, True, vbMonday) '
would return 'Sun'
Return To Top
Format
function with Dates
‘
the Format function takes an expression and returns it as a formatted
string. The syntax is:
Format(expression, [format, [firstdayofweek, [firstweekofyear]]])
‘
expression is the value to format. format
is optional. You can either define your own format or use the
predefined formats (General Date, Long Date, Medium Date, Short Date,
Long Time, Medium Time, Short Time). firstdayofweek is
optional and is defined in the previous example. firstweekofyear
is optional. If this parameter is omitted, the Format function
assumes that the week that contains January 1 is the first week of the
year.
firstweekofyear
argument
can be one of the following values:
Constant
Value Description
vbUseSystem 0 Uses the NLS API setting
vbFirstJan1 1 The week that contains January
1
vbFirstFourDays 2 The first week that has at least
4 days in the year
vbFirstFullWeek 3 The first full week of the year
Format("Aug 19, 2007", "General Date"
'
returns '8/19/2007'
Format(#8/19/2007#, "Short Date")
'
returns '8/19/2007'
Format(#8/19/2007#, "Medium Date")
'
returns '19-Aug-07'
Format(#8/19/2007#, "Long Date")
‘
returns 'Sunday, August 19, 2007'
Format(#8/19/2007#, "yyyy/mm/dd")
'
returns '2007/08/19'
Format("23.59:59", "Long time")
'
returns '11:59:59 PM'
Format("23.59:59", "Medium time")
'
returns '11:59 PM'
Format("23.59:59", "Short time")
'
returns '23:59'
Below is an
example of user-defined date and time formats for Aug 19, 1962:
Format
Display as:
Format("Aug 19, 1962", "m/d/yy")
'
returns '8/19/62'
Format("Aug 19, 1962", "d-mmm")
'
returns '19-Aug'
Format("Aug 19, 1962", "d-mmmm-yy")
‘
returns '19-August-62'
Format("Aug 19, 1962", "d mmmm")
‘
returns '19 August'
Format("Aug 19, 1962", "mmmm yy")
'
returns 'August 62'
Format("Aug 19, 1962", "hh:mm AM/PM")
'
returns '12:00 AM'
Format("Aug 19, 1962", "h:mm:ss am/pm")
‘
returns '12:00:00 am'
Format("Aug 19, 1962", "h:mm")
'
returns '0:00'
Format("Aug 19, 1962", "h:mm:ss")
'
returns '0:00:00'
Format("Aug 19, 1962", "m/d/yy h:mm:ss")
'
returns '8/19/62 0:00:00'
Return To Top
Now
function
‘ it
returns the current system date and time. This function will refresh the
date/time value whenever the worksheet recalculates or by pressing the
F9 key.
Dim ThisTimeToday As Date
ThisTimeToday = Now()
DatePart function
’
returns a Variant (Integer) containing the specified part of a given
date. The optional firstdayofweek and firstweekofyear
arguments are used to specify how the date should be calculated when
certain interval codes are used. If
firstdayofweek
parameter is omitted, Excel assumes that Sunday is the first day of the
week. If firstweekofyear
parameter is omitted, Excel assumes that the week containing Jan 1st is
the first week of the year.
DatePart(interval, date, [firstdayofweek], [firstweekofyear])
’
this example shows you specified parts of a date that you are asked to
input.
Dim FirstDate As String, SecondDate As String
FirstDate = InputBox("Enter a date:")
' as
in your system's default date format
SecondDate = Format(FirstDate, "long date")
Range("A1") = SecondDate
Range("A2").Value = "Your date entered as: " & CDate(FirstDate)
Range("A3") = "Quarter: " & DatePart("q", FirstDate)
Range("A4") = "Year: " & DatePart("yyyy", FirstDate)
Range("A5") = "Month: " & DatePart("m", FirstDate)
Range("A6") = "Day: " & DatePart("d", FirstDate)
Range("A7") = "Day of Year: " & DatePart("y", FirstDate)
Range("A8") = "Weekday: " & DatePart("w", FirstDate)
Range("A9") = "Week: " & DatePart("ww", FirstDate)
Return To Top
Day
function
‘
returns the day of the month (a number from 1 to 31) given a date value
Dim x As Date
Range("A1").Select
ActiveCell.Value = #8/19/1962#
x = ActiveCell
ActiveCell.Offset(, 1) = "which is Day " & Day(x) ‘ or
simply as Day(#8/19/1962#)
Hour function
’
returns the hour of a time value (from 0 to 23). The syntax is:
Hour(time)
= Hour(#11:59:58 AM#)
‘
returns ‘11’
= Hour(#11:59:58 PM#)
‘
returns ‘23’
= Hour(#8/31/2005 11:59:58 PM#)
‘
returns ‘23’
= Hour(38595.9999768519)
‘
returns ‘23’
Minute
function
’
Minute function returns the minute of a time value (from 0 to 59). The
syntax is:
Minute(serial_number)
= Minute(#11:45:58 AM#)
'
returns '45'
= Minute(#11:50:58 PM#)
'
returns '50'
= Minute(#8/31/2005 11:59:58 PM#)
'
returns '59'
= Minute(38595.9999768519)
'
returns '59'
Return To Top
DateSerial function
’ In
example below the variable MyDate would now contain the date for the
specified year, month, and day.
The syntax is:
DateSerial(year, month, day)
Dim MyDate As Date
MyDate = DateSerial(1962, 8, 19)
‘
returns ‘8/19/1962’
MyDate = DateSerial(1962 + 10, 8, 19)
‘
returns ‘8/19/1972’
TimeSerial function
’
returns a time given an hour, minute, and second value. hour is a
numeric value between 0 and 23; minute is a numeric value between 0 and
59; second is a numeric value between 0 and 59
TimeSerial(hour, minute, second)
Dim MyTime As Date
MyTime = TimeSerial(23, 59, 58)
'
returns ‘11:59:58 PM’
MyTime = TimeSerial(23 - 1, 59, 58)
'
returns ‘10:59:58 PM’
MyTime = TimeSerial(23, -59, 58)
'
returns ‘10:01:58 PM’
MyTime = TimeSerial(23, -59, -58)
'
returns ‘10:00:02 PM’
Return To Top |