0% found this document useful (0 votes)
16 views

Macros (SPE Lab)

The document contains examples of macros in VBA for Excel that demonstrate: 1) Calculating the sum of a selected range of cells 2) Checking if a user-input number is positive, negative, or zero 3) Determining a student's grade based on their score

Uploaded by

Hrishikesh Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Macros (SPE Lab)

The document contains examples of macros in VBA for Excel that demonstrate: 1) Calculating the sum of a selected range of cells 2) Checking if a user-input number is positive, negative, or zero 3) Determining a student's grade based on their score

Uploaded by

Hrishikesh Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

Calculate Sum

Sub CalculateSum()

Dim selectedRange As Range

Dim cell As Range

Dim sumValue As Double

' Check if a range is selected

On Error Resume Next

Set selectedRange = Application.InputBox("Select a range of cells:", Type:=8)

On Error GoTo 0

If Not selectedRange Is Nothing Then

' Calculate the sum of values in the selected range

For Each cell In selectedRange

sumValue = sumValue + cell.Value

Next cell

' Display the result in a message box

MsgBox "Sum of selected range: " & sumValue

Else

MsgBox "No range selected."

End If

End Sub
2. Positive or negative

Sub CheckNumber()

Dim num As Double

' Prompt the user to enter a number

num = InputBox("Enter a number:")

' Check if the number is positive, negative, or zero

If num > 0 Then

MsgBox "The number is positive."

ElseIf num < 0 Then

MsgBox "The number is negative."

Else

MsgBox "The number is zero."

End If

End Sub

3. Grade check

Sub CheckGrade()

Dim score As Integer

Dim grade As String

' Get the student's score from cell A1

score = Range("A1").Value
' Determine the grade based on the score

Select Case score

Case Is >= 90

grade = "A"

Case Is >= 80

grade = "B"

Case Is >= 70

grade = "C"

Case Is >= 60

grade = "D"

Case Else

grade = "F"

End Select

' Display the grade in a message box

MsgBox "The student's grade is: " & grade

End Sub

4. Sum of first 10 integers

Sub CalculateSum()

Dim total As Integer

Dim counter As Integer total = 0

' Loop from 1 to 10 and add each value to the total

For counter = 1 To 10 total = total + counter Next counter


' Display the total in a message box MsgBox "The sum of numbers from 1 to 10 is: " & total
End Sub

5. Sum of first 10 integers using foreach

Sub CalculateSum()

Dim total As Integer

Dim counter As Integer

total = 0

' Loop from 1 to 10 and add each value to the total

For counter = 1 To 10

total = total + counter

Next counter

' Display the total in a message box

MsgBox "The sum of numbers from 1 to 10 is: " & total

End Sub

6. Do While Loop in Excel

Sub CalculateFactorialWhileLoop()

Dim number As Integer

Dim factorial As Long

number = InputBox("Enter a positive integer:")

factorial = 1
Do While number > 0

factorial = factorial * number

number = number - 1

Loop

MsgBox "Factorial is: " & factorial

End Sub

7. The smallest power of 2 greater than 1000 using do untill

Sub FindPowerOf2UntilLoop()

Dim powerOf2 As Long

Dim exponent As Integer

powerOf2 = 1

exponent = 0

Do Until powerOf2 > 1000

exponent = exponent + 1

powerOf2 = 2 ^ exponent

Loop

MsgBox "The smallest power of 2 greater than 1000 is 2^" & exponent & " = " &
powerOf2

End Sub
8. Calculate Rectangle Area

Sub CalculateRectangleArea()

Dim length As Double

Dim width As Double

Dim area As Double

length = InputBox("Enter the length of the rectangle:")

width = InputBox("Enter the width of the rectangle:")

area = length * width

MsgBox "The area of the rectangle is: " & area

End Sub

9. Excel Object Model

Sub CreateTableExample()

Dim newWorksheet As Worksheet

Set newWorksheet = ThisWorkbook.Sheets.Add

' Set the name of the new worksheet

newWorksheet.Name = "DataSheet"

' Add headers to the first row

newWorksheet.Cells(1, 1).Value = "Name"


newWorksheet.Cells(1, 2).Value = "Age"

newWorksheet.Cells(1, 3).Value = "City"

' Add data to the table

newWorksheet.Cells(2, 1).Value = "John"

newWorksheet.Cells(2, 2).Value = 30

newWorksheet.Cells(2, 3).Value = "New York"

newWorksheet.Cells(3, 1).Value = "Alice"

newWorksheet.Cells(3, 2).Value = 25

newWorksheet.Cells(3, 3).Value = "Los Angeles"

End Sub

10. Using For Each...Next Loop with a Range of Cells

Sub ColorCellsExample()

Dim cell As Range

Dim targetRange As Range

' Set the range of cells to be colored

Set targetRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A5")

' Loop through each cell in the range and change the background color

For Each cell In targetRange

cell.Interior.Color = RGB(255, 255, 0) ' Yellow color

Next cell
End Sub

11. Macro Finding Roots by Bisection

Function MyFunction(x As Double) As Double

' Define your function here

' For example: MyFunction = x^3 - 2*x - 5

MyFunction = x ^ 3 - 2 * x - 5

End Function

Sub BisectionMethod()

Dim a As Double, b As Double

Dim tolerance As Double

Dim midPoint As Double

' Set the interval [a, b] and the tolerance

a=1

b=2

tolerance = 0.0001

' Perform bisection method

Do While (b - a) >= tolerance

midPoint = (a + b) / 2

If MyFunction(midPoint) = 0 Then

Exit Do
ElseIf MyFunction(a) * MyFunction(midPoint) < 0 Then

b = midPoint

Else

a = midPoint

End If

Loop

MsgBox "Root: " & midPoint

End Sub

12. Macros Using Arrays

Sub CalculateSumAndAverageUsingArrays()

Dim dataRange As Range

Set dataRange = Range("A1:A10") ' Set the range containing the data

Dim dataArray() As Variant

dataArray = dataRange.Value ' Store the data in an array

Dim totalSum As Double

Dim dataCount As Long

totalSum = 0

dataCount = UBound(dataArray, 1) - LBound(dataArray, 1) + 1 ' Get the number of


elements

Dim i As Long

For i = LBound(dataArray, 1) To UBound(dataArray, 1)

totalSum = totalSum + dataArray(i, 1) ' Sum the values

Next i
Dim average As Double

average = totalSum / dataCount ' Calculate the average

' Display the results

MsgBox "Total Sum: " & totalSum & vbNewLine & "Average: " & average

End Sub

You might also like