Professional Documents
Culture Documents
EXERCISE:
Create a function that display a 3 by 4 matrix in cells A1:D3, containing elements from 1 to 12 in two
ways:
Function matrix() As Variant
Dim v() As Variant
Dim N As Long
Dim r As Long
Dim c As Long
ReDim v(1 To 3, 1 To 4)
For r = 1 To 3
For c = 1 To 4
N = N + 1
v(r, c) = N
Cells(r, c) = v(r, c) 'this displays in horizontal order all the
numbers between 1 and 12 in a 3 by 4 matrix'
Next c
Next r
test = v
End Function
EXERCISE 2
SOLUTION:
Sub display_matrix()
Dim arr(3, 3) As Variant
For i = 1 To 3
For j = 1 To 3
arr(i, j) = i + j
Next j
Next i
MsgBox (arr(1, 1))
Pos1=inputbox(enter the first position)
Pos2=inputbox(enter the second position)
MsgBox(arr(Pos1,Pos2))
End Sub
EXERCISE 3
Given 2 integers lower and upper(limits) create an array that displays all the elements from lower to
upper.
SOLUTION:
Function LoadNumbers(low As Long, High As Long) As Long()
Dim ResultArray() As Long
Dim Ndx As Long the index
Dim Val As Long
If low > High Then
Exit Function
End If
ReDim ResultArray(1 To (High - low + 1))
Val = low
For Ndx = LBound(ResultArray) To UBound(ResultArray)
ResultArray(Ndx) = Val
Val = Val + 1
Next Ndx
LoadNumbers = ResultArray() 'not ResultArray but with ()'
End Function
Sub Atest()
Dim arr() As Long
Dim N As Long
arr = LoadNumbers(low:=101, High:=110)
For N = LBound(arr) To UBound(arr)
MsgBox (arr(N))
Next N
End Sub
EXERCISE 4
Create two functions:one that computes the sum of even numbers from a range and another that
computes the average of the elements from a range.
'Functions of ranges'
Function sumevennumbers(rng As Range)
'declare now a range object and call it cell'
Dim cell As Range
For Each cell In rng
If cell.Value Mod 2 = 0 Then
sumevennumbers = sumevennumbers + cell.Value
End If
Next 'this is for ending the For Each loop'
End Function
EXERCISE 5
Create a Macro (Sub routine) that whenever you click on a cell, it prints down Sales,Production,Logistic
each one line under the other.
SOLUTION:
Sub typing()
'
' typing Macro
'
'
ActiveCell.FormulaR1C1 = "sales"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "production"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "logistics"
ActiveCell.Offset(1, 0).Range("A1").Select
End Sub
EXERCISE 6
Given a number entered from the input box, call it n,and a clicked cell, write a macro that starting from
that cell writes Hello on each cell, n times.
SOLUTION:
Sub typing4()
'
'typing4 Macro
'
'
n = InputBox("enter the number of cells")
For i = 1 To n
ActiveCell.FormulaR1C1 = "Hello"
ActiveCell.Offset(1, 0).Range("A1").Select
Next
End Sub
EMPTYSHEET and Message Boxes
'Message boxes'
Sub message_box1()
MsgBox "this is fun"
MsgBox "The entered values is" & Range("A1").Value
MsgBox "This is:" & vbNewLine & " a new message"
Application.Volatile
MsgBox "Range(A1).Value" & vbNewLine & Range("A1").Value & vbNewLine &
Range("A2").Value
End Sub
REMARK:& inside MsgBox is used for newline