Excel Vba Programminw: Ceaneering
Excel Vba Programminw: Ceaneering
Contents
• Introduction (Excel VBA Editor, Tools, etc.)
• Excel VBA and Variables
• Conditional Logic
• String and String Functions
• Programming Loops
• Programming Arrays
• Stubs and Functions
• Excel VBA and Text Files
• Excel VBA and User Forms
Chapter 1 Introduction
If you have Excel 2007, click the round Office button, then click Excel Options at the bottom. When you
get the Options dialogue box up, click on Popular from the left in 2007. In the section labeled "Top options
for working with Excel" check the box for "Show Developer tab in the Ribbon":
When you have the developer toolbar, you'll see the following tab in the Ribbon (this is
from Excel 2013, so you may not have all the items below):
In Excel 2010 and 2013 click the File menu then select Options. From the dialogue
box, click on Customize Ribbon on the left side. From the right hand side you'll then
see an area called "Customize the Ribbon". Under "Main Tabs" check the box
for Developer:
When you have the developer toolbar, you'll see the following tab in the Ribbon (this is
from Excel 2013, so you may not have all the items below):
In order to run macros without any annoying security warnings, click on Macro
Security, on the Code panel. Select the option for Enable all macros. Then make sure
that "Trust access to the VBA object model" is checked:
NOTE: If you're worried about macro security then you can always bring this box up
again and disable the macros before you exit Excel.
Now that you have the developer tab added to the Ribbon you can do things like bring up the
Visual Basic Editor, run macros, record macros, and insert form objects onto your spreadsheets.
First, let's have a look at the Visual Basic Development Environment. This is, after all, where
you'll be writing all your code.
There are a few ways to open up the VBA Editor in Excel. From the Developer tab, on the Code
panel, you can click the Visual Basic button. On the Controls panel of the Developer tab, you
can click View Code.
To give you a quick idea of what VBA code looks like, add the following in the white
area for Sheet1:
Sub HelloWord()
End Sub
The Sub at the start of our code is short for Subroutine. A Subroutine is just a chunk of
code that does a particular job. It has a corresponding End Sub to show where the
code chunk ends. (What you should have noticed, though, is that as soon as you typed
the first line and hit the Enter key VBA adds the End Sub for itself.)
A Sub needs a name followed by a pair of round brackets. There is a space between
Sub and the name. In between Sub and End Sub is where you add the code for your
macro. You can have practically anything you like as a name for your Subroutines. But
try to keep them related to what the code will be doing. If we'd give our Sub the name
Colin, for example, it would be a bit odd, to say the least. The Name HelloWorld
describes what the code will do, however.
Sub Hello_World()
Take note of the following when coming up with a name for your Subroutines:
They can't start with a number, only alphabetical characters (you can have
numbers elsewhere in your names, though)
You can't have full stops/periods in them
You can't use any of the following characters anywhere in your names: #, $, %,
&, !
Once you've added the code, it's time to run it. To run your code, have a look at the
toolbar at the top of the editor. Locate and click the green triangle:
Another way to run your code is to click the Run menu. From the Run menu, select Run
Sub/User Form.
If you have Windows 7 or greater you can easily have two programmes open side by
side by doing the following:
If the above doesn't work for you, then just position the two windows as best you can.
But we can now record a macro and watch as Excel does its thing.
On the Developer tab, locate the Code panel and click Record Macro:
For the Macro Name, type TestMacro. Click the dropdown box for Store macro in and
select Personal Macro Workbook:
Click OK.
To record the Macro, select the cells A1 to A6. Click on the Home tab on the Excel
ribbon. Locate the Alignment panel and click the right-align option:
Switch back to the Developer tab. On the Coding panel, click Stop Recording:
Now have a look at the coding window. If you haven't yet recorded a macro you should
see a new item appear in the object window, just below your sheet objects:
Double click Module1 and you'll see the code for the Macro you've just recorded:
(Don't worry if your coding window doesn't have the Option Explicit at the top. We'll
explain about this in the variables chapter, later.)
Excel has created a Sub of its own. You don't need to understand all the code at this
early stage. But you can probably pick out a few things that make sense. The cells A1 to
A6 appear on the first line (the green lines are comments and will be ignored). This
All those other lines highlight the fact that Excel tends to add lots of code unnecessarily.
When you get some experience writing VBA code you'll spot lots of ways you can
reduce the code Excel writes. For example, the whole of the macro above could have
been replaced with just one line. This
We'll explore Ranges in the next section. But this single line of code is more readable -
it reduces Excel's code to just the bare minimum.
Now that you've recorded a macro, click the File menu in the VB Editor. From the File
menu, select Save Personal.XLSB.
Let's try another macro. With this one, we'll just select the text and make it bold. Keep
Excel and the Coding Editor open side by side.
Return to Excel. Click on the Developer tab again, and click Record Macro on
the Code panel. You should see the Record Macro dialogue box appear. Change the
name from Macro2 to Make Bold. Leave Store macro in on Personal Macro
Workbook. Click OK.
Highlight cells A1 to A6 again. Click on the Home tab in the Ribbon. From
the Font panel, click the Bold icon.
Keep an eye on the coding window when you do all this. You should see Excel
automatically adding the code for you Sub. Something like this:
Range ("A1:A6").Select
Selection.Font.Bold = True
Stop the recording by clicking on the Developer tab, then the Code panel.
Objects/Methods/Properties of Excel
Here “Sheet” Name of Sheet or can input index of Sheet Sequence like in above code it 1. Both line of
code will do same task.
Workbooks
Worksheets
ActiveCell
Properties: - Range
Every Object has some properties like Worksheets has following Properties. It differentiate
object from each others.
Range
Visible
Count
Methods:-Add Quits
Every Object has some Methods (like action) that works on properties assigned. Like Methods
of Worksheets are
Add:-
There are five items on the Code panel: Visual Basic, Macros, Record Macro, Use
Relative References, and Macro Security. You've already seen the Macro Security item.
If you can't run your Macros then click this item and change the security settings.
Clicking the Visual Basic item opens up the Visual Basic editor. You can also press
ALT + F11 on your keyboard as a shortcut.
Clicking the Macros item on the Code panel brings up the following dialogue box:
Once you create a few Macros, they will appear in the list. You can then run them by
selecting a Macro Name and clicking the Run button.
The other two items are Record Macro and Use Relative References. We'll skip over
these two, as we won't have too much use for them.
The panel we'll use a lot, though, is the Controls panel. It looks like this:
The first item, Insert, is expanded when you click on it. Doing so will reveal the
following:
These are all the controls you can add to an Excel spreadsheet or a user form. We'll be
adding one of these controls to a spreadsheet shortly. But back to the Controls panel.
The other items are:
The View Code item takes you to the Visual Basic editor again.
We'll now create a Macro that selects a range of cells. These cells will be selected when
we click a button on a spreadsheet.
To create the Macro, click the Visual Basic item on the Code panel. The Visual Basic
Editor will open up. We want this Macro to be only for Sheet1 in the current Workbook.
On the left hand side of the Editor, locate the Project Explorer panel. (If you can't see it,
Click View > Project Explorer from the menu at the top of the Editor.)
In the Project Explorer right click the Sheet1 item under VBAProject (Book1):
From the menu that appears, select View Code. A blank coding window will open up.
(You can also double click on Sheet1 to open up the code window.)
What we want to do here is to create a Subroutine. This Subroutine will be our Macro.
Type the following line into the white coding area:
Sub Range_A1_D6()
Press the Enter key on your keyboard and the Editor should add the corresponding End
Sub for you. Your coding window will then look like this:
Range("A1:D6").Select
As you can guess, this code selects a range of cells. It selects the cells A1 to D6.
From the menu bar at the top of the Editor, click File > Save Book1. The Save As
dialogue box should appear. Change the name of the file to Range_Exercises.xlxs.
Click the Save button and you should see an error message appear. This one:
You get the error message because your file contains Macros. Excel can't save Macros
in a file that end in xlxs. You need to change the file ending. To do that, click the Save
As Type dropdown list. From the list, select Excel Macro-Enabled Workbook(*.xlsm):
Click the Save button again. When you click the Save button this time, the file should
save OK. But note that the file ending is now xlsm.
Now move your mouse to your spreadsheet. Hold down your left mouse button
somewhere on the F column (F3 will do). Keep it held down and draw out a rectangular
button. Let go of the left mouse button when your cursor is on H4
As soon as you let go of the left mouse button you'll see the Assign Macro dialogue
box appear:
Select your Macro from the list and click OK. The button on your spreadsheet should
now look like this:
You can edit the text on a button quite easily. Right click the button to see a menu
appear. From the menu, select Edit Text:
When you select Edit Text, a cursor will appear at the start of the text. Use the arrow
keys on your keyboard to move the cursor to the end of the line. Delete the text Button
1 and type
Range("A1").Offset(RowOffSet:=1, ColumnOffset:=1).Select
The above code will select cell B2. The location we've used is cell A1. We've then typed
a dot followed by the word Offset. In between round brackets, you tell Excel the new
location. This is done with the parameters RowOffSet and ColumnOffSet. (The two are
separated by a comma.) In other words, move one row from cell A1 and one column
from cell A1.
You can use a shorthand instead of RowOffSet and ColumnOffSet. The shorthand just
uses the numbers:
Range("A1").Offset(1, 1).Select
You can also just specify the Rows and not the columns:
Range("A1").Offset(1).Select
Here, we've missed off the column parameter and its comma. Excel takes this to mean
you want to move one row down from the cell you specified with Range. The cell
selected will now be A2. (We've gone down a row but stayed in the same column.)
Similarly, you can specify the columns but not the rows:
Range("A1").Offset(, 1 ).Select
Now, the row position is blank and the column position is filled in. Notice that we have
left in the comma, though. Excel takes this to mean that you don't want a new position
for the rows, just the columns. The cell selected will now be B1. (We've gone across
one column but stayed in the same row.)
Range("B2").Offset(-1, -1 ).Select
This time, we're starting in cell B2. In between the round brackets of Offset we have -1,
-1. A negative number means go up one row or column from the starting position. Going
up one row and one column from cell B2 takes you to cell A1.
You can also specify more than one cell for the Range:
22 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
Range("A1:C3").Offset(1, 1).Select
Here, we've started with the range of cells A1 to C3. We want to offset this entire range
by one row and one column. The new range of cells in the line of code above will be B2
to D4. When specifying a range of cells with offset, not only does the first cell (A1
above) get moved across and down 1 but the last cell (C3) gets moved across 1 and
down 1.
Return to your coding window from the previous lesson. Create another Sub and give it
the nameRange_Offset. Add the following code:
Range("A1").Offset(RowOffSet:=1, ColumnOffset:=1).Select
Your coding window will then look like this (we've added some comments):
Return to Excel and draw out another button on your spreadsheet. When the Assign
Macro dialogue box appears, select your new Sub, Range_Offset. Change the text on
the button, as well. To test it out, select the cell A1 on your spreadsheet. Then click your
button. You should find that Excel now selects cell B2:
Range("A1").Offset(2, 2).Select
Range("A1").Resize(RowSize:=2, ColumnSize:=2).Select
This is almost identical to the Offset code you used earlier. The only difference is the
word Resize instead of Offset. Again we start with a Range (cell A1). In between the
round brackets of Resize you type a RowSize and ColumnSize. Like before, though,
you can shorten this and just have the numbers between the round brackets:
Range("A1").Resize(2, 2).Select
If you only want to resize the rows then you can miss out the ColumnSize parameter:
Range("A1").Resize(2).Select
If you only want to resize the columns then you can miss out the RowSize parameter:
Range("A1").Resize(, 2).Select
Return to your coding window. Set up a new Sub and call it Range_Resize. In
between Sub and End Sub, type the following line:
Range("A1").Resize(RowSize:=2, ColumnSize:=2).Select
To test out your new button, click inside cell A1 just to highlight your starting position.
Now click the button. You should find that the cells A2 to B2 are highlighted:
In computer programming, you need to store things in memory, things like numbers and
strings of text. You store them so that you can retrieve them later and manipulate the
numbers or strings of text in some way. To store things in memory you use a variable.
Variables have a name (something that you yourself come up with) and a type (such as
Integer or String). In the Visual Basic programming language you also need to declare
that you are setting up a variable. This is done (mostly) with the word Dim. As an
example, study the following:
The above code sets up a variable with the name MyNumber. The type of variable is a
whole number (As Integer). The Dim keyword goes at the start, and tells the
programme to set up a variable of this name and type.
However, there's nothing stored inside of the MyNumber variable - VBA has just
allocated the memory at this point. To store something inside of a variable, you use the
equal sign (=), also known as the assignment operator. To store a value of 10, say,
inside of the variable called MyNumber, you do it like this:
MyNumber = 10
The above line reads, "Assign a value of 10 to the variable called MyNumber". So the
name of your variable comes first, then the equal sign. After the equal sign you type the
value that you want to store inside of your variable.
Sadly, you can't set up a variable and assign a value all on the same line. (You can in
Visual Basic .NET but not in Visual Basic for Applications.) So you can't do this:
Variable Names
You can call your variable just about anything you like. But there are a few things you're
not allowed to do. They are:
MyVariable
My_Variable
myvariable2
2MyVariable
My Variable
$myvariable
The first one above starts with a number, the second one has a space, and the third
starts with a dollar sign.
Option Explicit
In order to ensure that you don't have any variables that start with the Dim keyword,
you can typeOption Explicit at the very top of your coding window. What this does is to
instruct VBA to check your variables for you. Take the following code as an Example:
At the very top of the code we have Option Explicit. The Sub has one variable set up
with the Dim keyword - MyNumber. On the second line, we place a value of 1 in this
variable. On the third line, however, we have this:
MyNumbers = 2
The error message is telling us that there is an undeclared variable somewhere in our
code, a variable not set up with the Dim keyword. (NOTE: There are other keywords
besides Dim that you can start a variable declaration with. We haven't covered these
yet, though.)
So it's a good idea to type Option Explicit at the top of your code window in order to
prevent variables being set up accidentally.
General Declarations
If you look again at the top of the coding window, where we had Option Explicit, you'll
see two dropdown lists:
The first dropdown list says General. The second one says Declarations. But the
second one only says Declarations because we have clicked the cursor at the top of the
coding window. If you click inside of the Sub, the second list changes to the name of
that Sub.
You can set up variables at the top of your code, in the General Declarations area. If
you do, then those variables can be seen from anywhere in the code for that window.
You'll get some practice with variables set up in the General Declarations in a later
lesson. In the next lesson, you'll see how to add and subtract in Excel VBA.
Number_1 = 10
Number_2 = 20
Subtraction:-
In the VBA programming language, the minus sign (-) is used to subtract one value from
another. Again, you can use actual values, values stored in variables, or a combination
of the two.
Go back to your code. Set up another Sub and call it Subtract_Numbers. Add the
following lines of code:
Number_1 = 450
Number_2 = 387
Number_1 = 10
Number_2 = 5
Division
The symbol to use when you want to divide numbers is the forward slash (/). (Quite
bizarrely, though, you can also use the back slash (\) without getting any error
messages. You may get errors in your calculations, though)
Try out some division for yourself. Return to your coding window and add a new Sub.
Call itDivide_Numbers. In between Sub and End Sub, type the following code:
Number_1 = 10
Number_2 = 5
As well as declaring a variable to be of type Integer, as you have been doing so far, you
can also have the following numerical variable types:
As Long
As Single
The difference between all these numerical data types is how many digits they can hold,
and whether or not you want a decimal point (there is actually an As Decimal variable
type, but it's a bit fiddly to use).
The first one on the list, As Long, is a great alternative to As Integer. We've been using
As Integer exclusively up until now. The problem with the Integer variable type,
however, is that it can only hold numbers up to a value of 32, 767. At the lower level the
Integer variable type can only hold negative numbers up to -32, 768.
If you want store bigger numbers then clearly 32, 767 may not be enough. This is
where As Longcomes in. The Long variable type can hold positive numbers up to a
value of 2, 147, 483, 647. The lowest negative number is -2, 147, 483, 648.
But Integer and Long are both used to store whole numbers. They would be no good if
you wanted divide 10 by 3, say. If you want a remainder, you'll need a different variable
type.
The variable types you can use for greater precision are As Single and As Double.
The difference between the two are how many digits they can hold. As Single holds 4
bytes of data while As Doublecan hold 8 bytes. If you want a really, really long floating
point number (a number with "point something" at the end) then use As Double,
otherwise just use As Single.
Conditional Logic is all about the IF word. It's about saying what should happen IF a
certain condition is met, or what should happen if it's not met.
If Condition_To_Test Then
'CODE HERE
End If
You start with the word If (uppercase "I" lowercase "f"). After a space, you have a
condition that you want to test. This conditional is something that can either be TRUE or
FALSE. After your condition, you type a space followed by the word Then (uppercase
"T"). An If Statement ends with the wordsEnd If.
In Between If and End If is where you type your code. But this code will only be
executed IF your condition is TRUE. If it's FALSE then VBA skips past the End If and
continues on its way.
Let's clear things up with a few coding examples. You can start a new spreadsheet for
this. When you save the new file, don't forget to save it as an Excel Macro- Enable
Workbook. The file ending will then be XLSM.
Else
Between If and End If you can also add an Else part. The structure of an If …
Else Statement looks like this:
If Condition_To_Test Then
Else
End If
32 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
ElseIf
Not every condition can be reduced to a simple either/or. Quite often, you'll have more
than two options you want to check for. In our code, we may want to check for a value
of 10, 11, and any other number. This is where ElseIf comes in. Here's the structure of
an ElseIf Statement:
If Condition_To_Test Then
End If
You can have more than one ElseIf parts, as many as you need, in fact:
If Condition_To_Test Then
End If
Notice that the only difference between If and ElseIf is the word Else tacked on to the
word If. You still have a condition to test and the keyword Then at the end.
You can also add an Else part, to catch anything you may have missed:
If Condition_To_Test Then
Else
End If
By using the various Operators, you can set up more sophisticated conditions for your If
Statements.
Only the first three are used regularly. Let's see how they works. Before doing so,
however, there's one more important variable type we need to discuss - Boolean values.
You can set up something called a Boolean variable. Boolean variables have only two
values: eithertrue or false. You set them up like this:
BooleanFlag = True
Else
End If
The first line test if the variable called BooleanFlag is equal to a value of True. If it is,
then we display a message. Because there are only two options, we can just have an
Else part to test for all other values, as any other value will be False.
You can miss out the = True part, if you like, and just have this:
If BooleanFlag Then
VBA will then take this to mean "If BooleanFlag has a value of True".
With all that in mind, let's take a look at the Not operator.
Code section 1
Else
Code section 2
End if
Code section 1
Else
Code Section 2
End if
MsgBox "Red"
MsgBox "Green"
MsgBox "Blue"
Else
MsgBox "None"
36 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
End If
But you can use Select Case for this instead. Examine the following:
Case "R"
MsgBox "Red"
Case "G"
MsgBox "Green"
Case "B"
MsgBox "Blue"
Case Else
MsgBox "None"
End Select
A Select Case statement begins with the words Select Case. You then type the thing
you're testing for. This can be a variable, a number, text in double quotes, and even a
built-in Excel function. For each possible answer, you then have one Case. Each Case
is evaluated to TRUE or FALSE. If it's TRUE then the code for that Case gets executed.
Only one Case per Select statement will get executed. The whole thing ends with the
words End Select.
In the code above, we're saying "If it's the Case that the variable User_Choice contains
the letter R Then display a message box saying Red." If it's not TRUE then VBA drops
down to the next Case and check if that's TRUE. You can have an optional Case
Else to catch anything else that the value at the beginning could be. So
if User_Choice does not contain an R, a G or a B then we display a message saying
"None".
You can check for more than one value by using the word To. For example, if you want
to check a range of ages you can do it like this:
Case 0 To 35
You can also check several values at once. Simply separate each one with a comma:
37 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
Case 10, 20, 30, 40
VBA will now only see the above Case as TRUE if the value you're selecting for is 10,
20, 30, or 40. Any other values and this Case will evaluate to FALSE.
Let's have a look at a more practical example, though. We'll go back to our student
score spreadsheet so that you can get some practice with Select Case in Excel VBA.
We'll do that in the next lesson below.
.property
End With
ActiveCell.Font.Bold = True
ActiveCell.Font.Color = vbBlue
ActiveCell.Font.Name = "Arial"
ActiveCell.Font.Size = 22
ActiveCell.Font.Italic = True
But notice the repetition here. We've used ActiveCell.Font five times. By using a With
Statement, we can just type the ActiveCell.Font once. Like this:
With ActiveCell.Font
.Bold = True
.Color = vbBlue
.Name = "Arial"
.Size = 22
.Italic = True
End With
Setting up a variable to hold text is quite straightforward. You simply Dim a variable As
String:
To store text inside of your variable you need to surround it with double quotes:
Even if you place numbers between double quotes they still gets treated as text and not
Integers:
MyString = "25"
The above line means store 25 as text, and NOT store the number 25.
ActiveCell.Value = MyString
MyString = ActiveCell.Value
Quite often, though, you'll need to do something with the text that you get from a cell on
a spreadsheet. For example, you may need to take a full name from one cell and place
the first name in another cell and the surname in yet another. To do things like this, you
need to know how to use Excel VBA's built-in string functions. The functions we'll study
are these:
LCase,
UCase
Trim and Len
Space
Replace
StrReverse
InStr, InStrRev
Left, Right
Mid
Range("A2").Offset(, 3).Value =
Application.WorksheetFunction.Proper(FullName)
"some text"
Create another Sub in your code window. Call it TrimAndLen. Add the following code:
LengthFullName = Len(FullName)
MsgBox LengthFullName
Space
You might actually want to pad out a string with blank space. If so, the Space function is
the one you want. In between the round brackets, you type a number. This number is
how many space characters you want. Here's some code to illustrate this:
MsgBox Len(FullName)
The first message box display a value of 13, which is how many characters are in the
name David Gilmour. The second message box displays a value of 18, the 13 original
characters, plus 5 added to the start of the name.
o use the Replace function, you need at least three things between it round brackets:
The first thing you need is a string of text to search. Next, you specify what it is you're
searching for. This is the character or characters you're going to replace. The third thing
you need is the new character or characters.
With the Replace function you also have an optional three things you can specify.
These are:
The optional parameters go after the third item in replace, with each being separated by
a comma:
The start parameter is where in the string you want to start search from. The default is
character 1, which is the first character in the string. If you want to start from a position
in the string other than the first character then you need to type your start number here.
The count parameter is how many occurrences you want to replace. The default is to
replace every occurrence of replace_with. If you only want to replace, say, the first two
occurrences then type the number 2 here.
Email = "myaddress@myisp.com"
Location = InStr(Email, "@")
MsgBox Location
StrReverse
This one is quite easy to use. As its name suggest StrReverse reverses the letters in a
string of text. Here's some code to try:
ReversedText = StrReverse(OriginalText)
MsgBox (ReversedText)
When the code is run, the message box will display "txet emos", which is "some text"
reversed.
44 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
Email = "myaddress@myisp.com"
MsgBox Left(Email, 9)
MsgBox Right(Email, 9)
The first part is the string you want search. This can be a variable or direct text between
double quotes. The second part is where in the string you want to start grabbing
characters from. The final part is how many characters you want to grab.
Email = "myaddress@myisp.com"
MsgBox GrabbedChars
Sub LoopExample()
EndNumber = 5
MsgBox StartNumber
Next StartNumber
End Sub
For Each loops are normally used with collections and arrays (you'll learn about Arrays
in a later lesson). This just means that you have one or more items to cycle through. It's
still a For loop, though. But this time the word "Each" follows the word "For", with a
space between the two. The Each part means "Each individual item in the collection or
array". The structure of a For Each loop looks like this:
Next variable_name
Cells Property
As well as referring to cells on a spreadsheet with Range you can use Cells. The Cells
property has an Item property that you use to reference the cells on your spreadsheet:
Cells.Item(Row, Column)
EndNumber = 5
Next StartNumber
Do While [CONDITION]
Loop
After Do While on the first line, you need a condition to test. This is usually the same
sort of thing you did in the Conditional Logic section. For example:
Do While x < y
Here, the loop goes round and round until the test condition at the start evaluates to
FALSE. As soon as VBA detects that your test condition is FALSE it will exit the loop
and continue on its way.
Do Until Loop
A loop that's closely related to the Do While loop is the Do Until loop. You use them the
same way, except instead of typing While you type Until. When you're using Until,
though, the end condition will change slightly. Here it is for the Do While Loop:
Counter = counter + 1
Loop
Counter = counter + 1
Loop
Chapter 6 Arrays
An array is a way to store more than one value under the same name. An array looks
like this when it is declared:
MyArray(0) = 10
MyArray(1) = 20
MyArray(2) = 30
MyArray(3) = 40
MyArray(4) = 50
To get a value back out of any array, it's just like any other variable: put it on the right of
an equal sign:
ArrayValue = MyArray(1)
Multidimensional Arrays
To Create an array with more than one dimension, you simply add a comma after the
first number between the round brackets of your array name, then add another number.
Like this:
Or like this:
MyArray(0, 0) = 10
MyArray(0, 1) = 10
This means row 0 columns 0 has a value of 10, row 0 column 1 has a value of 10, row 0
column 2 has a value of 10, and row 0 column 3 has a value of 10.
A Sub is a small chunk of code that you write to do a specific job. You can run this Sub
by pressing F5 in the VBA Editor, you can run it by assigning the Sub to a button on a
spreadsheet, and you can even run it from the menu bar at the top of the Editor. In fact,
there's quite a lot of different ways you can run your Subs.
The way you activate one Sub from inside another is to simply type its name. Optionally,
you can add the word Call at the start of the line. Like this:
Call SecondCode
The reason they both show up is that by default they are Public Subs. This means that
they can be seen just about everywhere from Excel. If you don't want a Sub showing up
in the Assign Macro dialogue box then you can make it Private. The way you make a
Sub Private is by typing the wordPrivate before the word Sub:
End Sub
If you miss out the "As Variable_Type" then the variables are treated As Variant. Notice
that you don't need the Dim word anymore.
But this is just setting up the variable. They have nothing in them yet. To place
something in these variables, you do so on the calling line.
Exit Sub
Sometimes, it's useful to exit a subroutine early. For example, you can have some error
checking at the start of a Sub. If a value not what you want, you can bail out. The way
you do this is with the wordsExit Sub.
MsgBox("Number Required")
MSGBOX(“5”)
Functions are Subroutines (Sub) are the same only difference is Function
return some values Subroutines does not return any value.
End function
You start with the word Function. After a space, you need to come up with a name for
your function. Like Sub names, this should be something relevant to what the function
does.
Defination :-
Calling:-
ReturnValue = CheckCell(ActiveCell.Value)
58 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
If your file has comma separated values, you can save it with the ending in .csv or .txt.
Files ending incsv are, however, a common format, and we'll stick with those types of
files.
If a file has each item on a line separated with the Tab character then it is said to be a
TXT file. They look like this:
Go to VBA Editor
Create UserForm with Drag, Drop and Move Control in Form area.
To Write Code for each Control event, Just double click on control then it will show VBA
Code Editor Window .
Go back to your spreadsheet and add a new button. When the Assign Macro dialogue
box appears, select Button1_Click:
Sub Button1_Click( )
UserForm1.Show
End Sub
If you don't want to place a button on the spreadsheet itself, you can add a new button
to the ribbon at the top of Excel. In Excel 2007, however, you can only add items to the
Quick Access toolbar which appears at the very top:
Starting from Excel 2010, you can customize the ribbon itself, adding new tabs and new
groups. We'll do that in the next lesson. If you only have Excel 2007, then here's how to
launch your form from the Quick Access toolbar.
First, we need to create new Sub in the Excel VBA Editor. We can then add our
UserForm1.Show code to this Sub. Doing it this way means we don't have to have a
button on the spreadsheet that launches the form.
66 IT Corporate (Application)| Oceaneering
Excel VBA Programming 2014
From the Project Explorer on the left, double click on Module1:
When you double click Module1 you should see a new coding window open. Add the
following code to the window:
Sub CallUserForm( )
UserForm1.Show
End Sub
With the Sub created in the Module window, it will now appear as a macro when we
customize the Quick Access toolbar.
So click the round Office button at the top left of Excel 2007. Click on Excel Options at
the bottom:
When you click on Excel Options, you'll see Options dialogue box appear. Click
on Customize from the list on the left:
Now click the dropdown list at the top and select Macros from the list:
When you select Macros, you should see the CallUserForm Sub appear in the listbox
below it.
The listbox on the right shows all the commands added to the Quick Access toolbar.
The first one is Save, then Undo, then Redo, and finally our CallUserForm macro.
Click OK on the Modify button dialogue box. Click OK on the Options dialogue box as
well to return to Excel.
Take a look at the Quick Access toolbar at the top of Excel 2007 and you'll see the icon
you selected: