Documente Academic
Documente Profesional
Documente Cultură
VBA - Generalitati
Ce este VBA?
Click OK.
You can find the Developer tab next to the View tab.
Setari de securitate legate de macro-uri
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
Result:
Visual Basic Editor
Range("B3").Value = 2
Range("A1:A4").Value = 5
Range Examples
Range("A1:A2,B3:C4").Value = 10
Cells
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
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
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
Dim x As Integer
x=6
Range("A1").Value = 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: 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
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
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
Result:
Result:
Right
Result:
Mid
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
Result:
Result:
Note: Use Month and Day to get the month and day of a
date.
DateAdd
To get the current date and time, use the Now function.
Code:
MsgBox Now
Result:
Result:
Note: Use Minute and Second to get the minute and second
of a time.
TimeValue
Result:
TimeValue
Result:
Events
Workbook Open Event
Result:
Arrays
One-dimensional Array
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
Area = x * y
End Function
Function
z = Area(3, 5) + 2
MsgBox z
Function
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
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
• Range("A3").Value = "=AVERAGE(A1:A2)“
Speed tuning VBA
Speet tuning VBA
screenUpdateState = Application.ScreenUpdating
statusBarState = Application.DisplayStatusBar
statusDisplayAlerts = Application.DisplayAlerts
calcState = Application.Calculation
eventsState = Application.EnableEvents
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
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
Now when you change the value of cell A1, the value of cell
B1 is not recalculated.
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = screenUpdateState
Application.DisplayStatusBar = statusBarState
Application.DisplayAlerts = statusDisplayAlerts
Application.Calculation = calcState
Application.EnableEvents = eventsState
Select the range B2:B4 and click the command button (make
sure Design Mode is deselected).
Result:
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
'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
• 'Empty MoneyTextBox
MoneyTextBox.Value = ""
End Sub
MoneyTextBox.Text = MoneySpinButton.Value
End Sub
Explanation: this code line updates the text box when you
use the spin button.
Assign the Macros
'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
End Sub
Assign the Macros
Call UserForm_Initialize
End Sub
Explanation: this code line calls the Sub
UserForm_Initialize when you click on the Clear button.
Assign the Macros
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: