Sunteți pe pagina 1din 141

VBA

VBA - Generalitati
Ce este VBA?

 Abrevierea de la Visual Basic Applications


 Un limbaj de scriere a macro-urilor
 Un limbaj de programare orientat pe evenimente (event-
driven) utilizat in aplicatiile Microsoft Excel, Word, etc.
 O versiune a limbajului de programare Visual Basic, ce
contine tool-uri, functii si metode customizate pentru lucrul
cu obiectele unei aplicatii
 Este continut in pachetul MS Office, deci este gratis
Cum lucreaza macrourile VBA pentru Excel

 Macro-urile Excel automatizeaza task-uri complexe si


repetitive ale Excel
 Macro-urile (codul VBA) se pot inregistra, scrie si edita.
 Macro-urile sunt salvate fie intr-un anume fisier Excel fie pot
fi salvate global – pentru apelarea lor din mai multe fisiere
 Macro-urile pot fi asociate unor evenimente cum ar fi: click,
dublu-click, etc. si astfel pot rula la producerea respectivului
eveniment
 Se pot adauga obiecte de genul: butoane (buttons),
casute text (textboxes), etc. si scrie apoi cod VBA
pentru fiecare dintre acestea
 Editorul VB (VBE) este parte a Excel si cu ajutorul acestuia
se pot vizualiza, edita si rula macrouri
Developer Tab

 To turn on the Developer tab, execute the following steps.


 Right click anywhere on the ribbon, and then click
Customize the Ribbon.

 Under Customize the Ribbon, on the right side of the


dialog box, select Main tabs (if necessary).
Developer Tab

 Check the Developer check box.


Developer Tab

 Click OK.
 You can find the Developer tab next to the View tab.
Setari de securitate legate de macro-uri

 In Excel fisierele care contin macro-uri au intotdeauna


extensia .xlsm
 La deschiderea unui fisier .xlsm, daca nivelul de securitate al
macrourilor este mediu va aparea mesajul
“Security Warning. Macro has been disabled”
Setari de securitate legate de macro-uri

 Click pe Options si apare fereastra de mai jos


 Daca fisierul este dintr-o sursa sigura si doriti accesul la
macro-uri dati click pe Enable Macros.
Create a macro
Command Button

 To place a command button on your worksheet, execute the


following steps.
 On the Developer tab, click Insert.
 In the ActiveX Controls group, click Command Button.

 Drag a command button on your worksheet.


Error messages saying “Can’t insert object”

 To fix it, do this:


 1.Close all Office applications.
 2.Do a search in Windows Explorer – make sure to
include hidden and system files and folders – for *.exd
files (note: that’s not *.exe !!) and delete any you find.
 Make sure you get these:
• C:\users\username\AppData\Local\Temp\Excel8.0\MSForms.exd
• C:\users\username\AppData\Local\Temp\VBE\MSForms.exd
 3.Reboot the computer (this is not always necessary, but
probably better safe than sorry)
 4.Restart your Office apps and test the controls again.
Assign a Macro

 To assign a macro (one or more code lines) to the command


button, execute the following steps.
 Right click CommandButton1 (make sure Design Mode
is selected).
 Click View Code.
Assign a Macro

 The Visual Basic Editor appears.


 Place your cursor between
Private Sub CommandButton1_Click() and End Sub.
 Add the code line shown below.

 Note: The window on the left with the names Sheet1, Sheet2
and Sheet3 is called the Project Explorer. If the Project
Explorer is not visible, click View, Project Explorer. To add
the Code window for the first sheet, click Sheet1 (Sheet1).
Assign a Macro

 Close the Visual Basic Editor.


 Click the command button on the sheet (make sure Design
Mode is deselected).

 Result:
Visual Basic Editor

 To open the Visual Basic Editor, on the Developer tab, click


Visual Basic.
Visual Basic Editor

 The Visual Basic Editor appears


Message Box - MsgBox
MsgBox

 The MsgBox is a dialog box in Excel VBA you can use to


inform the users of your program. Place a command button
on your worksheet and add the following code lines:
 MsgBox "This is fun“

 MsgBox "Entered value is " & Range("A1").Value

 Note: we used the & operator to concatenate (join) two


strings. Although Range("A1").value is not a string, it works
here.
MsgBox

 To start a new line in a message, use vbNewLine.


 MsgBox "Line 1" & vbNewLine & "Line 2"
Workbook and Worksheet Object
Object Hierarchy

 In Excel VBA, an object can contain another object, and that


object can contain another object, etc. In other words, Excel
VBA programming involves working with an object hierarchy.
This probably sounds quite confusing, but we will make it
clear.
 The mother of all objects is Excel itself. We call it the
Application object. The application object contains other
objects. For example, the Workbook object (Excel file). This
can be any workbook you have created. The Workbook
object contains other objects, such as the Worksheet object.
The Worksheet object contains other objects, such as the
Range object.
Object Hierarchy

 We used the following code line:


 Range("A1").Value = "Hello“
 but what we really meant was:
 Application.Workbooks("create-a-
macro").Worksheets(1).Range("A1").Value = "Hello“
 Note: the objects are connected with a dot. Fortunately, we
do not have to add a code line this way. That is because we
placed our command button in create-a-macro.xls, on the
first worksheet. Be aware that if you want to change different
things on different worksheets to include the Worksheet
object.
Collections

 Workbooks and Worksheets are both plural. That is because


they are collections. The Workbooks collection contains all
the Workbook objects that are currently open. The
Worksheets collection contains all the Worksheet objects in
a workbook.

 You can refer to a member of the collection, for example, a


single Worksheet object, in three ways.
Collections

 1. Using the worksheet name.


 Worksheets("Sales").Range("A1").Value = "Hello"
 2. Using the index number (1 is the first worksheet starting
from the left).
 Worksheets(1).Range("A1").Value = "Hello"
 3. Using the CodeName.
 Sheet1.Range("A1").Value = "Hello"
Collections

 To see the CodeName of a worksheet, open the Visual Basic


Editor. In the Project Explorer, the first name is the
CodeName. The second name is the worksheet name
(Sales).
Collections

 Note: the CodeName remains the same if you change the


worksheet name or the order of your worksheets so this is
the safest way to reference a worksheet.
 Click View, Properties Window to change the CodeName of
a worksheet.
 There is one disadvantage, you cannot use the CodeName if
you reference a worksheet in a different workbook.
Properties and Methods

 Properties are something which an collection has (they


describe the collection), while methods do something (they
perform an action with an collection).
 Place a command button on your worksheet and add the
code lines:
 1. The Add method of the Workbooks collection creates
a new workbook.
• Workbooks.Add
 Note: the Add method of the Worksheets collection
creates a new worksheet.
 2. The Count property of the Worksheets collection
counts the number of worksheets in a workbook.
• MsgBox Worksheets.Count
 Result when you click the command button on the sheet:
Properties and Methods

 Note: the Count property of the Workbooks collection counts


the number of active workbooks.
Range object
Range Object

 The Range object, which is the representation of a cell (or


cells) on your worksheet, is the most important object of
Excel VBA. This chapter gives an overview of the properties
and methods of the Range object. Properties are something
which an object has (they describe the object),
while methods do something (they perform an action with an
object).
Range Examples

 Range("B3").Value = 2

 Range("A1:A4").Value = 5
Range Examples

 Range("A1:A2,B3:C4").Value = 10
Cells

 Instead of Range, you can also use Cells. Using Cells is


particularly useful when you want to loop through ranges.

 Cells(3, 2).Value = 2

 Explanation: Excel VBA enters the value 2 into the cell at the
intersection of row 3 and column 2.
Cells

 Range(Cells(1, 1), Cells(4, 1)).Value = 5


Declare a Range Object

 You can declare a Range object by using the keywords Dim


and Set.
 Code:
 Dim example As Range
 Set example = Range("A1:C4")
 example.Value = 8
Select

 An important method of the Range object is the Select


method. The Select method simply selects a range.
 Code:
 Dim example As Range
 Set example = Range("A1:C4")
 example.Select
Rows

 The Rows property gives access to a specific row of a range.


 Code:
 Dim example As Range
 Set example = Range("A1:C4")
 example.Rows(3).Select
Columns

 The Columns property gives access to a specific column of a


range.
 Code:
 Dim example As Range
 Set example = Range("A1:C4")
 example.Columns(2).Select
Copy/Paste

 The Copy and Paste method are used to copy a range and
to paste it somewhere else on the worksheet.
 Code:
 Range("A1:A2").Select
 Selection.Copy
 Range("C3").Select
 ActiveSheet.Paste

 Although this is allowed in Excel VBA, it is much better to


use the code line below which does exactly the same.
 Range("C3:C4").Value = Range("A1:A2").Value
Clear

 To clear the content of an Excel range, you can use the


ClearContents method.
 Range("A1").ClearContents
 Note: use the Clear method to clear the content and format
of a range. Use the ClearFormats method to clear the format
only.
Count

 With the Count property, you can count the number of cells,
rows and columns of a range.

 Code:
 Dim example As Range
 Set example = Range("A1:C4")
 MsgBox example.Count
Variables

 This chapter teaches you how to declare, initialize and


display a variable in Excel VBA. Letting Excel VBA know you
are using a variable is called declaring a variable. Initializing
simply means assigning a beginning (initial) value to a
variable.

 Place a command button on your worksheet and add the


code lines below. To execute the code lines, click the
command button on the sheet.
Integer

 Integer variables are used to store whole numbers.

 Dim x As Integer
 x=6
 Range("A1").Value = x

 Result:

 Explanation: the first code line declares a variable with name


x of type Integer. Next, we initialize x with value 6. Finally,
we write the value of x to cell A1.
String

 String variables are used to store text.


 Code:
 Dim book As String
 book = "bible“
 Range("A1").Value = book
 Result:

 Explanation: the first code line declares a variable with name


book of type String. Next, we initialize book with the text
bible. Always use apostrophes to initialize String variables.
Finally, we write the text of the variable book to cell A1.
Double

 A variable of type Double is more accurate than a variable of


type Integer and can also store numbers after the comma.
 Code:
 Dim x As Integer
 x = 5.5
 MsgBox "value is " & x
 Result:

 But that is not the right value! We initialized the variable with
value 5.5 and we get the value 6. What we need is a variable
of type Double.
Double

 Code:
 Dim x As Double
 x = 5.5
 MsgBox "value is " & x
 Result:

 Note: Long variables have even larger capacity. Always use


variables of the right type. As a result, errors are easier to
find and your code will run faster.
Boolean

 Use a Boolean variable to hold the value True or False.


 Code:
 Dim continue As Boolean
 continue = True
 If continue = True Then MsgBox "Boolean variables are
cool"
 Result:

 Explanation: the first code line declares a variable with name


continue of type Boolean. Next, we initialize continue with
the value True. Finally, we use the Boolean variable to only
display a MsgBox if the variable holds the value True.
If Then Statement

 Use the If Then statement in Excel VBA to execute code


lines if a specific condition is met.
 Place a command button on your worksheet and add the
following code lines:
 Dim score As Integer, result As String
 score = Range("A1").Value
 If score >= 60 Then result = "pass"
 Range("B1").Value = result

 Explanation: if score is greater than or equal to 60, Excel


VBA returns pass. Note: if score is less than 60, Excel VBA
places the value of the empty variable result into cell B1.
Else Statement

 Place a command button on your worksheet and add the


following code lines:
 Dim score As Integer, result As String
 score = Range("A1").Value
 If score >= 60 Then
 result = "pass"
 Else
 result = "fail"
 End If
 Range("B1").Value = result

 Explanation: if score is greater than or equal to 60, Excel


VBA returns pass, else Excel VBA returns fail.
Else Statement

 Result when you click the command button on the sheet:

 Note: only if you have one code line after Then and no Else
statement, it is allowed to place a code line directly after
Then and to omit (leave out) End If (first example).
Otherwise start a new line after the words Then and Else
and end with End If (second example).
Loop
Loop

 Looping is one of the most powerful programming


techniques. A loop in Excel VBA enables you to loop through
a range of cells with just a few codes lines.
Single Loop

 You can use a single loop to loop through a one-dimensional


range of cells.
 Place a command button on your worksheet and add the
following code lines:
 Dim i As Integer
 For i = 1 To 6
 Cells(i, 1).Value = 100
 Next I
 Result:
Single Loop

 Explanation: The code lines between For and Next will be


executed six times. For i = 1, Excel VBA enters the value
100 into the cell at the intersection of row 1 and column 1.
When Excel VBA reaches Next i, it increases i with 1 and
jumps back to the For statement. For i = 2, Excel VBA enters
the value 100 into the cell at the intersection of row 2 and
column 1, etc.

 Note: it is good practice to always indent (tab) the code


between the words For and Next. This makes your code
easier to read.
Double Loop

 You can use a double loop to loop through a two-


dimensional range of cells.
 Place a command button on your worksheet and add the
following code lines:
 Dim i As Integer, j As Integer
 For i = 1 To 6
 For j = 1 To 2
 Cells(i, j).Value = 100
 Next j
 Next i
 Result:
Double Loop

 Explanation: For i = 1 and j = 1, Excel VBA enters the value


100 into the cell at the intersection of row 1 and column 1.
 When Excel VBA reaches Next j, it increases j with 1 and
jumps back to the For j statement. For i = 1 and j = 2, Excel
VBA enters the value 100 into the cell at the intersection of
row 1 and column 2.
 Next, Excel VBA ignores Next j because j only runs from 1 to
2. When Excel VBA reaches Next i, it increases i with 1 and
jumps back to the For i statement. For i = 2 and j = 1, Excel
VBA enters the value 100 into the cell at the intersection of
row 2 and column 1, etc.
Triple Loop

 You can use a triple loop to loop through two-dimensional


ranges on multiple Excel worksheets.
 Place a command button on your worksheet and add the
following code lines:
 Dim c As Integer, i As Integer, j As Integer
 For c = 1 To 3
 For i = 1 To 6
 For j = 1 To 2
 Worksheets(c).Cells(i, j).Value = 100
 Next j
 Next i
 Next c
Triple Loop

 Explanation: The only change made compared to the code


for the double loop is that we have added one more loop and
added Worksheets(c). in front of Cells to get the two-
dimensional range on the first sheet for c = 1, the second
sheet for c = 2 and the third sheet for c = 3. Download the
Excel file to see this result.
Do While Loop

 Besides the For Next loop, there are other loops in Excel
VBA. For example, the Do While Loop. Code placed
between Do While and Loop will be repeated as long as the
part after Do While is true.
 1. Place a command button on your worksheet and add the
following code lines:
 Dim i As Integer
 i=1
 Do While i < 6
 Cells(i, 1).Value = 20
 i=i+1
 Loop
Do While Loop

 Result

 Explanation: as long as i is lower than 6, Excel VBA enters


the value 20 into the cell at the intersection of row i and
column 1 and increments i by 1.
 In Excel VBA (and in other programming languages), the
symbol '=' means becomes. It does not mean equal. So i = i
+ 1 means i becomes i + 1. In other words: take the present
value of i and add 1 to it.
 For example, if i = 1, i becomes 1 + 1 = 2. As a result, the
value 20 will be placed into column A five times (not six
because Excel VBA stops when i equals 6).
Do While Loop

 2. Enter some numbers in column A.

 3. Place a command button on your worksheet and add the


following code lines:
 Dim i As Integer
 i=1
 Do While Cells(i, 1).Value <> ""
 Cells(i, 2).Value = Cells(i, 1).Value + 10
 i=i+1
 Loop
Do While Loop

 Result:

 Explanation: as long as Cells(i, 1).Value is not empty (<>


means not equal to), Excel VBA enters the value into the cell
at the intersection of row i and column 2, that is 10 higher
than the value in the cell at the intersection of row i and
column 1.
 Excel VBA stops when i equals 7 because Cells(7, 1).Value
is empty. This is a great way to loop through any number of
rows on a worksheet.
Macro Errors
Macro Errors

 Place a command button on your worksheet and add the


following code lines:
 x=2
 Range("A1").Valu = x
 Click the command button on the sheet.
 Result:

 Click OK.

 The variable x is not defined. Because we are using the
Option Explicit statement at the start of our code, we have to
declare all our variables. Excel VBA has colored the x blue to
indicate the error.
Macro Errors

 In the Visual Basic Editor, click Reset to stop the debugger.


 Correct the error by adding the following code line at the
start of the code.
 Dim x As Integer
 You may have heard of the technique called debugging
before. With this technique you can step through your code.
Macro Errors

 In the Visual Basic Editor, place your cursor before Private


and press F8.
 The first line turns yellow.

 Press F8 three more times.


Macro Errors

 The following error appears.


Macro Errors

 The Range object has a property called Value. Value isn't


spelled correctly here.
 Debugging is a great way to not only find errors, but also
understand code better.
 Our Debugging example program shows you how to single
step through your code and see the effect of each code line
on your worksheet.
String Manipulation
Join Strings

 We use the & operator to concatenate (join) strings.


 Code:
 Dim text1 As String, text2 As String
 text1 = "Hi“
 text2 = "Tim“
 MsgBox text1 & " " & text2

 Result:

 Note: to insert a space, use " "


Left

 To extract the leftmost characters from a string, use Left.


 Code:
 Dim text As String
 text = "example text“
 MsgBox Left(text, 4)

 Result:
Right

 To extract the rightmost characters from a string, use Right.


We can also directly insert text in a function.
 Code:
 MsgBox Right("example text", 2)

 Result:
Mid

 To extract a substring, starting in the middle of a string, use


Mid.
 Code:
 MsgBox Mid("example text", 9, 2)

 Result:

 Note: started at position 9 (t) with length 2. You can omit the
third argument if you want to extract a substring starting in
the middle of a string, until the end of the string.
Len

 To get the length of a string, use Len.


 Code:
 MsgBox Len("example text")

 Result:

 Note: space (position 8) included!


Instr

 To find the position of a substring in a string, use Instr.


 Code:
 MsgBox Instr("example text", "am")

 Result:

 Note: string "am" found at position 3.


Date and Time
Year, Month, Day of a Date

 The following macro gets the year of a date. To declare a


date, use the Dim statement. To initialize a date, use the
DateValue function.
 Code:
 Dim exampleDate As Date
 exampleDate = DateValue("Jun 19, 2010")
 MsgBox Year(exampleDate)
 Result:

 Note: Use Month and Day to get the month and day of a
date.
DateAdd

 To add a number of days to a date, use the DateAdd


function. The DateAdd function has three arguments. Fill in
"d" for the first argument to add days. Fill in 3 for the second
argument to add 3 days. The third argument represents the
date to which the number of days will be added.
 Code:
 Dim firstDate As Date, secondDate As Date
 firstDate = DateValue("Jun 19, 2010")
 secondDate = DateAdd("d", 3, firstDate)
 MsgBox secondDate
 Result:

 Note: The format of the result depends on computer date


settings
DateAdd

 Note: Change "d" to "m" to add a number of months to a


date. Place your cursor on DateAdd in the Visual Basic
Editor and click F1 for help on the other interval specifiers.
Dates are in US Format. Months first, Days second. This
type of format depends on your windows regional settings.
Current Date and Time

 To get the current date and time, use the Now function.
 Code:
 MsgBox Now

 Result:

 Note: The format of the result depends on computer date


and time settings
Hour, Minute, Second

 The get the hour of a time, use the Hour function.


 Code:
 MsgBox Hour(Now)

 Result:

 Note: Use Minute and Second to get the minute and second
of a time.
TimeValue

 The TimeValue function converts a string to a time serial


number. The time's serial number is a number between 0
and 1. For example, noon (halfway through the day) is
represented as 0.5.
 Code:
 MsgBox TimeValue("9:20:01 am")

 Result:
TimeValue

 Now, to clearly see that Excel handles times internally as


numbers between 0 and 1, add the following code lines:
 Dim y As Double
 y = TimeValue("09:20:01")
 MsgBox y

 Result:
Events
Workbook Open Event

 Code added to the Workbook Open Event will be executed


by Excel VBA when you open the workbook.
 Open the Visual Basic Editor.
 Double click on This Workbook in the Project Explorer.
 Choose Workbook from the left drop-down list. Choose
Open from the right drop-down list.
Workbook Open Event

 Add the following code line to the Workbook Open Event:


 MsgBox "Good Morning"
 Save, close and reopen the Excel file.
 Result:
Worksheet Change Event

 Code added to the Worksheet Change Event will be


executed by Excel VBA when you change a cell on a
worksheet.
 Open the Visual Basic Editor.
 Double click on a sheet (for example Sheet1) in the
Project Explorer.
 Choose Worksheet from the left drop-down list. Choose
Change from the right drop-down list.
Worksheet Change Event

 Add the following code lines to the Worksheet Change


Event:
 The Worksheet Change Event listens to all changes on
Sheet1. We only want Excel VBA to do something if
something changes in cell B2. To achieve this, add the
following code lines:
• If Target.Address = "$B$2" Then
End If
 We only want Excel VBA to show a MsgBox if the user
enters a value greater than 80. To achieve this, add the
following code line between If and End If.
• If Target.Value > 80 Then MsgBox "Goal Completed"
 On Sheet1, enter a number greater than 80 into cell B2.
Worksheet Change Event

 Result:
Arrays
One-dimensional Array

 An array is a group of variables. In Excel VBA, you can refer


to a specific variable (element) of an array by using the array
name and the index number.
 To create a one-dimensional array, execute the following
steps.
 Place a command button on your worksheet and add
the following code lines:
• Dim Films(5) As String
• Films(1) = "Lord of the Rings"
• Films(2) = "Speed"
• Films(3) = "Star Wars"
• Films(4) = "The Godfather"
• Films(5) = "Pulp Fiction"
• MsgBox Films(4)
One-dimensional Array

 Result when you click the command button on the sheet:

 Explanation: the first code line declares a String array with


name Films. The array consists of five elements. Next, we
initialize each element of the array. Finally, we display the
fourth element using a MsgBox.
Two-dimensional Array

 To create a two-dimensional array, execute the following


steps. This time we are going to read the names from the
sheet.
Two-dimensional Array

 Place a command button on your worksheet and add the


following code lines:
• Dim Films(5, 2) As String
Dim i As Integer, j As Integer

For i = 1 To 5
For j = 1 To 2
Films(i, j) = Cells(i, j).Value
Next j
Next i

MsgBox Films(4, 2)
 Result when you click the command button on the sheet:
Two-dimensional Array

 Explanation: the first code line declares a String array with


name Films. The array has two dimensions. It consists of 5
rows and 2 columns. Tip: rows go first, then columns. The
other two variables of type Integer are used for the Double
Loop to initialize each element of the array. Finally, we
display the element at the intersection of row 4 and column
2.
Function and Sub
Function and Sub

 The difference between a function and a sub in Excel VBA is


that a function can return a value while a sub cannot.
Functions and subs become very useful as program size
increases.
 Function
 If you want Excel VBA to perform a task that returns a
result, you can use a function. Place a function into a
module (In the Visual Basic Editor, click Insert, Module).
For example, the function with name Area.
• Function Area(x As Double, y As Double) As Double

Area = x * y

End Function
Function

 Explanation: This function has two arguments (of type


Double) and a return type (the part after As also of type
Double). You can use the name of the function (Area) in your
code to indicate which result you want to return (here x * y).
 You can now refer to this function (in other words call the
function) from somewhere else in your code by simply using
the name of the function and giving a value for each
argument.
 Place a command button on your worksheet and add the
following code lines:
• Dim z As Double

z = Area(3, 5) + 2

MsgBox z
Function

 Explanation: The function returns a value so you have to


'catch' this value in your code. You can use another variable
(z) for this. Next, you can add another value to this variable
(if you want). Finally, display the value using a MsgBox.
 Result when you click the command button on the sheet:
Sub

 If you want Excel VBA to perform some actions, you can use
a sub. Place a sub into a module (In the Visual Basic Editor,
click Insert, Module). For example, the sub with name Area.
• Sub Area(x As Double, y As Double)

MsgBox x * y

End Sub
 Explanation: This sub has two arguments (of type Double). It
does not have a return type! You can refer to this sub (call
the sub) from somewhere else in your code by simply using
the name of the sub and giving a value for each argument.
 Place a command button on your worksheet and add the
following code line:
• Area 3, 5
Sub

 Result when you click the command button on the sheet:

 Can you see the difference between the function and the
sub? The function returned the value 15. We added the
value 2 to this result and displayed the final result. When we
called the sub we had no more control over the result (15)
because a sub cannot return a value!
Application Object
Application Object

 The mother of all objects is Excel itself. We call it


the Application object. The application object gives access to
a lot of Excel related options.
 WorksheetFunction
 You can use the WorksheetFunction property in Excel
VBA to access Excel functions.
 For example, place a command button on your
worksheet and add the following code line:
• Range("A3").Value =
Application.WorksheetFunction.Average(Range("A1:A2"))
 When you click the command button on the worksheet, Excel
VBA calculates the average of the values in cell A1 and cell
A2 and places the result into cell A3.
WorksheetFunction

 Note: instead of Application.WorksheetFunction.Average,


simply use WorksheetFunction.Average. If you look at the
formula bar, you can see that the formula itself is not
inserted into cell A3. To insert the formula itself into cell A3,
use the following code line:

• Range("A3").Value = "=AVERAGE(A1:A2)“
Speed tuning VBA
Speet tuning VBA

 Turn off everything but the essentials while your code is


running
 This optimization explicitly turns off Excel functionality
you don’t need to happen while your code runs
 One reason this helps is that if you’re updating (via
VBA) several different ranges with new values, or copy /
pasting from several ranges to create a consolidated
table of data, you likely do not want to have Excel taking
time and resources to recalculate formulas, display
paste progress, or even redraw the grid, especially after
every single operation (even more so if your code uses
loops). Just one recalculation and one redraw at the end
of your code execution is enough to get the workbook
current with all your changes
Get current state of various Excel settings

screenUpdateState = Application.ScreenUpdating

statusBarState = Application.DisplayStatusBar

statusDisplayAlerts = Application.DisplayAlerts

calcState = Application.Calculation

eventsState = Application.EnableEvents

displayPageBreakState = ActiveSheet.DisplayPageBreaks ‘note


this is a sheet-level setting
ScreenUpdating

 This setting tells Excel to not redraw the screen while False.
As a result, your code will run faster.
 For example, place a command button on your
worksheet and add the following code lines:
• Dim i As Integer

For i = 1 To 10000
Range("A1").Value = i
Next i
 When you click the command button on the worksheet, Excel
VBA displays each value a tiny fraction of a second and this
can take some time.
 Be sure to turn it back on right before your code ends.
ScreenUpdating

 2. To speed up the process, update the code as follows.


• Dim i As Integer
• Application.ScreenUpdating = False
• For i = 1 To 10000
• Range("A1").Value = i
• Next i
• Application.ScreenUpdating = True
 As a result, your code will run much faster and you will only
see the end result (10000).
DisplayStatusBar

 This setting tells Excel to stop showing status while False.


 For example, if you use VBA to copy/paste a range, while
the paste is completing Excel will show the progress of that
operation on the status bar.
 Turning off screen updating is separate from turning off the
status bar display so that you can disable screen updating
but still provide feedback to the user, if desired.
 Turn it back on right before your code ends execution
DisplayAlerts

 You can instruct Excel VBA not to display alerts while


executing code.
 For example, place a command button on your
worksheet and add the following code line:
• ActiveWorkbook.Close
 When you click the command button on the worksheet, Excel
VBA closes your Excel file and asks you to save the changes
you made.
DisplayAlerts

 To instruct Excel VBA not to display this alert while executing


code, update the code as follows.
• Application.DisplayAlerts = False

ActiveWorkbook.Close

Application.DisplayAlerts = True
 As a result, Excel VBA closes your Excel file, without asking
you to save the changes you made. Any changes are lost.
Calculation

 By default, calculation is set to automatic. As a result, Excel


recalculates the workbook automatically each time a value
affecting a formula changes. If your workbook contains many
complex formulas, you can speed up your macro by setting
calculation to manual.
 For example, place a command button on your
worksheet and add the following code line:
• Application.Calculation = xlCalculationManual
 When you click the command button on the worksheet, Excel
VBA sets calculation to manual.

 You can verify this by clicking on File, Options, Formulas.


Calculation
Calculation

 Now when you change the value of cell A1, the value of cell
B1 is not recalculated.

 You can manually recalculate the workbook by pressing F9.


 In most situations, you will set calculation to automatic again
at the end of your code. Simply add the following code line to
achieve this.
• Application.Calculation = xlCalculationAutomatic
EnableEvents

 This setting tells Excel to not fire events while False.


 For example some desktop search tools implement event
listeners (probably to better track document contents as it
changes).
 You not want Excel firing an event for every cell you’re
changing via code, and turning off events will speed up your
VBA code performance if there is a COM Add-In listening in
on Excel events.
Turn off Excel functionality at the macro start

Application.ScreenUpdating = False

Application.DisplayStatusBar = False

Application.DisplayAlerts = False

Application.Calculation = xlCalculationManual

Application.EnableEvents = False

ActiveSheet.DisplayPageBreaks = False ‘note this is a sheet-


level setting
Restore state; Put this at the end of your code

Application.ScreenUpdating = screenUpdateState

Application.DisplayStatusBar = statusBarState

Application.DisplayAlerts = statusDisplayAlerts

Application.Calculation = calcState

Application.EnableEvents = eventsState

ActiveSheet.DisplayPageBreaks = displayPageBreaksState ‘note


this is a sheet-level setting
ActiveX Controls
ActiveX Controls

 Learn how to create ActiveX controls such as command


buttons, text boxes, list boxes etc. To create an ActiveX
control in Excel VBA, execute the following steps.
 On the Developer tab, click Insert.
 For example, in the ActiveX Controls group, click
Command Button to insert a command button control.
ActiveX Controls

 Drag a command button on your worksheet.


 Right click the command button (make sure Design Mode is
selected).
 Click View Code.
ActiveX Controls

 Note: you can change the caption and name of a control by


right clicking on the control (make sure Design Mode is
selected) and then clicking on Properties. Change the
caption of the command button to 'Apply Blue Text Color'.
For now, we will leave CommandButton1 as the name of the
command button.
 The Visual Basic Editor appears.
 Add the code line shown below between Private Sub
CommandButton1_Click() and End Sub.
ActiveX Controls

 Select the range B2:B4 and click the command button (make
sure Design Mode is deselected).
 Result:
Userform
Userform

 This chapter teaches you how to


create an Excel VBA Userform.
 The Userform we are going to
create looks as follows:
Userform

 Add the Controls


 To add the controls to the Userform, execute the following
steps.
 Open the Visual Basic Editor. If the Project Explorer is
not visible, click View, Project Explorer.
 Click Insert, Userform. If the Toolbox does not appear
automatically, click View, Toolbox. Your screen should
be set up as below.
Userform
Userform

 Add the controls listed in the table below. Once this has
been completed, the result should be consistent with the
picture of the Userform shown earlier. For example, create a
text box control by clicking on TextBox from the Toolbox.
Next, you can drag a text box on the Userform. When you
arrive at the Car frame, remember to draw this frame first
before you place the two option buttons in it.
 Change the names and captions of the controls according to
the table below. Names are used in the Excel VBA code.
Captions are those that appear on your screen. It is good
practice to change the names of controls. This will make
your code easier to read. To change the names and captions
of the controls, click View, Properties Window and click on
each control.
Userform

Control Name Caption


Userform DinnerPlannerUserForm Dinner Planner
Text Box NameTextBox
Text Box PhoneTextBox
List Box CityListBox
Combo Box DinnerComboBox
Check Box DateCheckBox1 June 13th
Check Box DateCheckBox2 June 20th
Check Box DateCheckBox3 June 27th
Frame CarFrame Car
Option Button CarOptionButton1 Yes
Option Button CarOptionButton2 No
Text Box MoneyTextBox
Spin Button MoneySpinButton
Command Button OKButton OK
Command Button ClearButton Clear
Command Button CancelButton Cancel
Name:, Phone Number:,
7 Labels No need to change
etc.
Userform

 Note: a combo box is a drop-down list from where a user can


select an item or fill in his/her own choice. Only one of the
option buttons can be selected.

 Show the Userform


 To show the Userform, place a command button on your
worksheet and add the following code line:
• Private Sub CommandButton1_Click()
• DinnerPlannerUserForm.Show
• End Sub
Userform

 We are now going to create the Sub UserForm_Initialize.


When you use the Show method for the Userform, this sub
will automatically be executed.
 Open the Visual Basic Editor.
 In the Project Explorer, right click on
DinnerPlannerUserForm and then click View Code.
 Choose Userform from the left drop-down list. Choose
Initialize from the right drop-down list.
 Add the following code lines:
Userform

• Private Sub UserForm_Initialize()

'Empty NameTextBox
NameTextBox.Value = ""

'Empty PhoneTextBox
PhoneTextBox.Value = ""

'Empty CityListBox
CityListBox.Clear

'Fill CityListBox
With CityListBox
.AddItem "San Francisco"
.AddItem "Oakland"
.AddItem "Richmond"
End With
Userform

• 'Empty DinnerComboBox
DinnerComboBox.Clear

'Fill DinnerComboBox
With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With

'Uncheck DataCheckBoxes
DateCheckBox1.Value = False
DateCheckBox2.Value = False
DateCheckBox3.Value = False

'Set no car as default


CarOptionButton2.Value = True
Userform

• 'Empty MoneyTextBox
MoneyTextBox.Value = ""

'Set Focus on NameTextBox


NameTextBox.SetFocus

End Sub

 Explanation: text boxes are emptied, list boxes and combo


boxes are filled, check boxes are unchecked, etc.
Assign the Macros

 We have now created the first part of the Userform. Although


it looks neat already, nothing will happen yet when we click
the command buttons on the Userform.
 Open the Visual Basic Editor.
 In the Project Explorer, double click on
DinnerPlannerUserForm.
 Double click on the Money spin button.
 Add the following code line:
• Private Sub MoneySpinButton_Change()

MoneyTextBox.Text = MoneySpinButton.Value

End Sub
 Explanation: this code line updates the text box when you
use the spin button.
Assign the Macros

 Double click on the OK button.


 Add the following code lines:
• Private Sub OKButton_Click()

Dim emptyRow As Long

'Make Sheet1 active


Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Cells(emptyRow, 1).Value = NameTextBox.Value
Cells(emptyRow, 2).Value = PhoneTextBox.Value
Cells(emptyRow, 3).Value = CityListBox.Value
Cells(emptyRow, 4).Value = DinnerComboBox.Value
Assign the Macros

• If DateCheckBox1.Value = True Then Cells(emptyRow, 5).Value


= DateCheckBox1.Caption

If DateCheckBox2.Value = True Then Cells(emptyRow, 5).Value


= Cells(emptyRow, 5).Value & " " & DateCheckBox2.Caption

If DateCheckBox3.Value = True Then Cells(emptyRow, 5).Value


= Cells(emptyRow, 5).Value & " " & DateCheckBox3.Caption

If CarOptionButton1.Value = True Then


Cells(emptyRow, 6).Value = "Yes"
Else
Cells(emptyRow, 6).Value = "No"
End If

Cells(emptyRow, 7).Value = MoneyTextBox.Value

End Sub
Assign the Macros

 Explanation: first, we activate Sheet1. Next, we determine


emptyRow. The variable emptyRow is the first empty row
and increases every time a record is added. Finally, we
transfer the information from the Userform to the specific
columns of emptyRow.
 Double click on the Clear button.
 Add the following code line:
• Private Sub ClearButton_Click()

Call UserForm_Initialize

End Sub
 Explanation: this code line calls the Sub
UserForm_Initialize when you click on the Clear button.
Assign the Macros

 Double click on the Cancel Button.


 Add the following code line:
• Private Sub CancelButton_Click()

Unload Me

End Sub
 Explanation: this code line closes the Userform when you
click on the Cancel button.
Test the Userform

 Exit the Visual Basic Editor, enter the labels shown below
into row 1 and test the Userform.
 Result:

S-ar putea să vă placă și