Excel2010
.pdf9.3.6.1 Selection statements
The most common selection statement is the If Then structure. It is used to decide. It has two essential and one optional part.
If (Boolean Expression) Then
Statement
Else
This part is optional
Statement
End if
Example 9.3:
You want to decide, according to his average, if a student has passed or failed. The students pass if their average is greater than or equal to 5. Student average is in D1 and you want to write the result to D2.
Sub Passes()
If Range("D1") < 5 Then
Result = "Failed"
Else
Result = "Passed"
End If
Range("D2") = Result
End Sub
Example 9.4:
In example 9.1, we had a sub procedure to delete selected cells. Now, add a message, whether the user is sure to delete. If he presses yes, the selected cells will be deleted.
Sub Macro1()
Name = InputBox("Enter your name please..:")
Res=MsgBox("Hello Mr." & Name & ". Are you sure?", _ vbYesNo,"Delete Record?")
If Res = vbYes Then
Selection.Delete Shift:=xlToLeft
End If
End Sub
Figure 9.10: Using InputBox and
MsgBox in Macros
Macros |
161 |
D1 is the parameter and its value is assigned to Num.
Figure 9.11:
Using Functions in Excel
9.3.6.2 Repeating some statements
Using For Next loops, you can repeat some operations:
For x = 1 To 10
' The code here will be repeated 10 times
Next x
Example 9.5:
Here is a function to calculate N!
Function NFactorial(Num As Integer)
Result = 1
For x = 1 To Num |
|
The loop is repeated Num |
|
times (7 in this example). |
|
Result = Result * x |
|
|
|
|
|
Next x |
|
|
x represents all numbers |
||
NFactorial = Result |
from 1 to num(7). Then, |
|
End Function |
Result is multiplied by all |
|
|
|
the numbers from 1 to 7. |
|
|
|
9.3.7 Object Browser
Object Browser gives short description and usage information about commands and objects. It shows class names and Members of the selected class. It also gives the properties of the member; either the member is property or a function of the class.
Write your command here to search
Figure 9.12: Object browser
162 |
Microsoft Excel |