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

VBA - Overview: TOPIC 1 - Introduction

1. VBA stands for Visual Basic for Applications, a programming language used to customize Microsoft Office applications like Excel. It allows users to build powerful tools in Excel using techniques like linear programming. 2. Some key uses of VBA in Excel include automating complex calculations that are difficult to do with formulas alone, like calculating loan repayments. 3. The document provides an introduction to VBA concepts like range objects and properties, cell objects, variables, and conditional logic structures like IF-THEN statements that allow programming logic and flow control.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

VBA - Overview: TOPIC 1 - Introduction

1. VBA stands for Visual Basic for Applications, a programming language used to customize Microsoft Office applications like Excel. It allows users to build powerful tools in Excel using techniques like linear programming. 2. Some key uses of VBA in Excel include automating complex calculations that are difficult to do with formulas alone, like calculating loan repayments. 3. The document provides an introduction to VBA concepts like range objects and properties, cell objects, variables, and conditional logic structures like IF-THEN statements that allow programming logic and flow control.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Page |1

TOPIC 1 – Introduction

VBA - Overview
VBA stands for Visual Basic for Applications an event-driven programming language from
Microsoft that is now predominantly used with Microsoft office applications such as
MSExcel, MS-Word, and MS-Access.
It helps techies to build customized applications and solutions to enhance the capabilities
of those applications. The advantage of this facility is that you NEED NOT have visual basic
installed on our PC, however, installing Office will implicitly help in achieving the purpose.
You can use VBA in all office versions, right from MS-Office 97 to MS-Office 2013 and also
with any of the latest versions available. Among VBA, Excel VBA is the most popular. The
advantage of using VBA is that you can build very powerful tools in MS Excel using linear
programming.

Application of VBA
You might wonder why to use VBA in Excel as MS-Excel itself provides loads of inbuilt
functions. MS-Excel provides only basic inbuilt functions which might not be sufficient to
perform complex calculations. Under such circumstances, VBA becomes the most obvious
solution.
For example, it is very hard to calculate the monthly repayment of a loan using Excel's
built-in formulas. Rather, it is easy to program a VBA for such a calculation.

Preparation of Microsoft Excel VBA

Activate developer tab in excel (Excel 2007 and up)


Go to “File”, then Click “Options”, then “Customize Ribbon” and check the “Developer” and
“OK” to enable the developer tab in excel.

Shortcut keys
Alt + F11 : Visual basic editor window
Ctrl + R Project Explorer
F4 Properties Windows
Page |2

Click new module


Type “sub groupname”
Type between Sub & End Sub
Range("a1") = 12
Then click play button (observe what happens on the excel sheet)
Next try
Range("a1:c6") = 12
Page |3

TOPIC 2 – Range Objects and Range Properties

1. Range object – same as cell in excel


Range object with cells

2. Range Properties:
a. .Value Property
MsgBox Range(“a1”).Value

b. .Text Property
MsgBox Range(“a1”).Text

c. .Row and .Column Property


MsgBox Range(“a1”).Text

d. .Select property
Range(“table_01”).Select

e. .Count Property
MsgBox Range(“table_01).Count

f. .ADDRESS PROPERTY
MsgBox Range(“a1”).Address(0,0)

g. .FORMULA PROPERTY
Range(“a1”).Formula = “=A2+A3”

h. .NUMBERFORMAT PROPERTY
Range(“a1”).NumberFormat = “0.00””mm”””

i. .FONT.BOLD, UNDERLINE OR ITALIC


Range(“a1”).Font.Bold = true
Range(“a1”).Font.Underline = true
Range(“a1”).Font.Italic = true
Page |4

EXERCISE 1
Objectives:
1. Create a Macro that types the following headers on row 1:
•ID
•First Name
•Last Name
2. Make the headers BOLD!

EXERCISE 2

Create a Macro that:


1. Enters the following data
2. Makes a1 through b1 BOLD
3. Selects cell C1
4. Now, manually create a shape that says Click Me and assign your macro to it. This is not part of
the macro, just make the shape manually.
Page |5

TOPIC 3 – Cell Objects

a. The Cell Object

Cells(1,2) = 50
Cells(1,”b”) = 50

b. Using Cells positionally within a Range


Cells(6) = 44
Range(“a1:c16”).cells(6) = 44

c. Affecting all cells in a worksheet


Cells.Font.Name = “Arial”
Cells.Font.Size = 15

d. Using Range Object with cells Object


Range(Cells(1,2),Cells(4,3)) = 4

EXERCISE 3
By default, Sheet1 on a worksheet will have a default cell font and will be zoomed to
100%.
In this exercise, the user wants a macro that formats a sheet to ideal conditions for
their work.
1. Format all cells as font "Arial"
2. Zoom in to
145%
3. Format Column D (4th column) as currency, because your company always has currency in
column D
Page |6

TOPIC 4 – Variables
a. Intro to Variables
Sub MyVar1()
MyVar = 50

b. Sub Var2()
Dim x As Integer, y As Integer
x = 10
y = 100
MsgBox "the value of x is " & x & Chr(13) & "the value of y is " & y
End Sub

c. Sub myVar3()
Dim hi as string
Dim hello As double
Dim mydate1 as Date

Hi = “Hello World”
Hello = 634.85
Mydate1 = “01/28/2019”
End Sub

d. Private and Public variables


Public myVar3
Sub MyVar1()
MyVar = 50
Call myVar3
MsgBox Hi
End Sub

e. Constant
Constant consname as string = “Bimby”
Page |7

EXERCISE 3

Continue with current procedure called 'getDaysOld' …


This procedure takes any Birthdate and reveals how many Days old someone
is.
1. Take today's date minus the entered date to get difference (number of days since
then)
2. Display "You are NNN days old" in a messagebox
3. BONUS! - Also display how many total hours old they are!
Page |8

TOPIC 5
Important Tools and Excel Logic

a. Determining the last rows in your data set


Ex. Last row in Column 1(row no.)
LastRow = cells(rows.count,1).end(xlup).row

b. Determining the last column in your data set


Ex. Last column in row 1
LastColumn = cells(1,columns.count).end(xltoleft).column

c. Determining the next row in your data set


Ex. Next row after the last row in Column 1(row no.)
NextRow = cells(rows.count,1).end(xlup).row+1

d. Absolute vs Relative references in Macro Recording

e. Using With and End With


With Range(“a1”)
.Font.Bold = true
.Font.Underline = true
.Font.Italic = true
End With

f. If then statement
Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Good!”
Page |9

End If
End Sub
g. If not equal to (<>) statement
Sub MyIfstatements()
If Range (“c6”) <> 12 Then
MsgBox “Good!”
End If
End Sub

h. If , Then, ElseIF Statement


Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Good!”
Else
MsgBox “Bad”
End If
End Sub

Another Example:
Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Twelve!”
Elseif Range(“c6”) = 5 then
MsgBox “Five”
Else
MsgBox “Please enter either a Five or a Twelve”
End If
End Sub

i. Comparative Operators with Text and Numbers


Note: VBA tend consider text somehow greater than any numbers so you'll have to
compensate

Sub MyIfstatements()
If Range("c6") > 3 And IsNumeric(Range("c6")) Then
MsgBox "Good!"
End If
End Sub

j. Select Case as alternative to IF THEN Statements


Sub myCase()
Select Case Range(“c6”)
Case 12
MsgBox “Twelve”
P a g e | 10

Case is <2
MsgBox “less than 2”
Case Else
MsgBox “else”
End Select

k. GoTo and Labels (Skip “underconstruction” codes)

Goto myEnding
.
.
myEnding:

l. Message box with Yes and No Options


Sub myMessage
Answer = MsgBox (“Do you like excel vba?”, vbyesNo)
If answer = vbYes Then
MsgBox “I like it too!”
Elseif answer = vbNo Then
Msgbox “I think you should like it, it’s cool!”
End If
End Sub

m. Relative positioning using Offset


Sub MyOffset
Selection.Offset(3,1) = Selection
Or
Cells(1,1).Offset(3,1)=”Mabuhay”
End Sub

n. User Defined function


Function MoI(b, d)
MoI = (b * (d ^ 3)) / 12
End Function

With optional parameter


Function MoI(b, d, Optional dplaces)
If IsMissing(dplaces) then
MoI = (b * (d ^ 3)) / 12
Else
MoI =Round(( (b * (d ^ 3)) / 12),dplaces)
End If
End Function
P a g e | 11

EXERCISE 4

NOTE: To get the row number of the Selected cell, use Selection.Row
When user clicks on a cell and clicks blue button, the macro will use items on that row in
various columns.

Create a Macro that does the following:


1. Asks user "Add 100 to current row sales?"
2. If Yes, add 100 to Sale Amount (current row, column 4)
3. If No, do nothing
4. Assign Macro to blue button
P a g e | 12

TOPIC 6 - Loops and Report Writing Basics

a. Intro to loops; the For Next Loop


Sub MyFirstLoop()
For X = 1 to 10
Cells(x, 1) = x
Next x
End Sub

Another sample:
Sub MyFirstLoop2()
For x = 1 to 10
Cells(x,1) = x * 12.75
If cells(x, 1) > 50 Then
Cells(x, 2) = True
Cells(x, 2).Font.Bold = True
Else
Cells(x, 2) = False
Cells(x, 2).Font.Bold = False
End IF
Next x
End Sub

b. Beginning our first Report using Loops


Sub myFirstReport()
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
P a g e | 13

For x = 2 To lastRow
If Cells(x, 4) >= 400 Then
myMsg = myMsg & vbNewLine & Cells(x, 1)
End If
Next x
MsgBox myMsg
End Sub

c. Using InputBox
Sub myIB()
myIB1 = InputBox("How much money should they make", "How Much", "200")
End Sub

d. Dynamic Report using InputBox


Sub myFirstReport()
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
myIB1 = InputBox("How much money should they make", "How Much", "200") +0
For x = 2 To lastRow
If Cells(x, 4) >= myIB1 Then
myMsg = myMsg & vbNewLine & Cells(x, 1)
End If
Next x
MsgBox myMsg
End Sub

Change MyMsg to:


myMsg = myMsg & vbNewLine & Cells(x, 1) & “, “ & Cells(x, 2)

e. Add Button to open our report


Using Command Button (ActiveX Control)
To be discuss manually

f. Add a “Cool Looking” Button or Image to Open Report


To be discuss manually

g. Printable Report: Declaring and Setting the Sheets


Sub myPrintableReport()

Dim dsheet As Worksheet


Dim rptsheet As Worksheet

Set dsheet = ThisWorkbook.Sheets(“data”)


Set rptsheet = ThisWorkbook.Sheets(“report”)
P a g e | 14

h. Printable Report : Getting Items on Report Sheet


Sub myPrintableReport()

Dim dsheet As Worksheet


Dim rptsheet As Worksheet

Set dsheet = ThisWorkbook.Sheets("Data")


Set rptsheet = ThisWorkbook.Sheets("report")

lastRow = dsheet. Cells(Rows.Count, 1).End(xlUp).Row


myIB1 = InputBox("How much money should they make", "How Much", "200") + 0

y = 2 'starting row

For x = 2 To lastRow
If dsheet.Cells(x, 4) >= myIB1 Then
rptsheet.Cells(y, 1) = dsheet.Cells(x, 1) 'name
rptsheet.Cells(y, 2) = dsheet.Cells(x, 4) 'sale amount
y=y+1
End If
Next x
End Sub

i. Clearing the Last Report


Input “rptLR” before “lastRow” variable
Let rptLR variable be the last row of the report

rptLR = rptsheet.Cells(Rows.Count, 1).End(xlUp).Row


rptsheet.Range("a2:b" & rptLR).ClearContents

j. Ensuring visibility and autoselect report sheet


Add this codes at the end of loops

rptsheet.Visible = True
rptsheet.Select

k. Using print preview automatically


add this before “End Sub”
rptsheet.PrintPreview

l. Handling debug error when cancelling input box


Insert:
On Error Resume Next
P a g e | 15

If myIB1 = Empty Then Exit Sub

m. Looping with specific interval or backward


Ex.
For x = 2 to 10 step .5
Or For x = 10 to 2 step -1

n. The For Each Loop


Ex.
Sub MyForeachloop()
For each cell in range(“names”)
Msgbox cell
Next cell
End Sub

o. To cancel the loop


Insert:
If cell = “any on the list” Then Exit For
EX:

Sub MyForeachloop()
For each cell in range(“names”)
IF cell = “Kellu” Then Exit For
Msgbox cell
Next cell
End Sub

p. Intro to DO LOOPS

Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop
End Sub

q. Do Until
Sub MyDoLoop()
X=2
Do Until Cells(x,1) = “”
P a g e | 16

MsgBox Cells(x,1)
x = x +1
Loop
End Sub

r. Loop Until
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop Until Cells(x,1) = “”
End Sub

s. Do While
Sub MyDoLoop()
X=2
Do While Cells(x,1) <> “”
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
t. Loop While
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop While Cells(x,1) <> “”
End Sub

u. Exit Do
Sub MyDoLoop()
X=2
Do
If Cells(x,1) = “” Then Exit Do
MsgBox Cells(x,1)
x = x +1
Loop
End Sub

v. Loop Through Multiple Files in a folder and Scrape Data From Each
Sub getDATAFromWbs()
P a g e | 17

Dim wb As Workbook, ws As Worksheet


Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.getfolder("C:\temp\")

For Each wbfile In fldr.Files

If fso.getextensionname(wbfile.Name) = "xlsx" Then

Set wb = Workbooks.Open(wbfile.Path)

For Each ws In wb.Sheets

Next ws

wb.Close

End If
Next wbfile
End Sub

Sub getDATAFromWbs2()
Dim wb As Workbook, ws As Worksheet
Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.getfolder("C:\temp\")

y = ThisWorkbook.Sheets("sheet1").Cells(Row.Count, 1).End(xlUp).Row + 1

For Each wbfile In fldr.Files


y = ThisWorkbook.Sheets("sheet1").Cells(Row.Count, 1).End(xlUp).Row + 1

If fso.getextensionname(wbfile.Name) = "xlsx" Then

Set wb = Workbooks.Open(wbfile.Path)

For Each ws In wb.Sheets

wsLR = ws.Cells(Rows.Count, 1).End(xlUp).Row

For x = 2 To wsLR
ThisWorkbook.Sheets("sheet1").Cells(y, 1) = ws.Cells(x, 1) '<<<<col1
ThisWorkbook.Sheets("sheet1").Cells(y, 2) = ws.Cells(x, 2) '<<<<col2
P a g e | 18

ThisWorkbook.Sheets("sheet1").Cells(y, 3) = CDate(ws.Cells(x, 1)) '<<<<col3


ThisWorkbook.Sheets("sheet1").Cells(y, 4) = ws.Cells(x, 4) '<<<<col4
y=y+1
Next x
Next ws

wb.Close

End If

Next wbfile
End Sub

EXERCISE 5

Add the following to the Existing Macro:


1. Add a Yes/No Messagebox to report with prompt "Use Title on
Report?"
2. If Yes, include Title information, if No, omit Title info on 3rd column.
3. BONUS: Create a separate procedure (copy/paste current macro) that prompts for User's Name

and only lists records with that user's name. Make a button or shape that triggers this other report.

EXERCISE 6
Create a procedure that:
1. Populate the table as in the image below. Attach procedure to the blue Shape as in previous exercises

2. Note: Each Name has a number that matches their ID and they go from 1 to 25 (Use a loop!)
3. BONUS: If the ID is greater than 17, make those cells in column A have a red background as below
P a g e | 19

TOPIC 7 – Worksheet Events

a. Intro to Worksheet Events and Selection_Change


Click Sheet1(Sheet1) on the Project Explorer then change into ‘Worksheet” on the upper
box.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)


If Target.Address(0, 0) = "C2" Then
MsgBox "You've got cell C2"
Else
MsgBox "Not Cell C2"
End If
End Sub
b. Worksheet Activate Events
Private Sub Worksheet_Activate()
MsgBox "Welcome to Sheet2"
End Sub

c. Worksheet Deactivate Events


Private Sub Worksheet_Deactivate()
Sheets("Sheet3").Visible = False
End Sub

d. BeforeDelete Event
Private Sub Worksheet_BeforeDelete()
MsgBox "Hala Bakit mo binura?"
End Sub

e. BeforeDoubleClick Event
P a g e | 20

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)


If Target.Address(0, 0) = "c3" Then
MsgBox "you double clicked c3"
Cancel = True
End If
End Sub

f. BeforeRightClick Event
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
If Target.Address(0, 0) = "C3" Then
MsgBox "you double right clicked c3"
Cancel = True
End If
End Sub

g. Calculate Event
Private Sub Worksheet_Calculate()
Columns("a:F").AutoFit
End Sub

h. Disable Events
Sub disableEvents()
Application.EnableEvents = False
End Sub

i. Intro to Change Event


Private Sub Worksheet_Change(ByVal Target As Range)
Stop
End Sub

j. Change Event with EnableEvents toggle


Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 Then
If Target.Offset(0, -1) = "Destiny" Then
Application.EnableEvents = False
Target = 0.75
Application.EnableEvents = True
End If
End If
End Sub

k. Change Event triggered with custom range using Intersect


Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("b2:b4")) Is Nothing Then
P a g e | 21

MsgBox "You changed something in b2:b4"


End If
End Sub

l. FollowHyperlink Event
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox Target.Name
End Sub

TOPIC 8 – Workbook Events

a. Workbook Open Event


Private Sub Workbook_Open()

Dim sh2 As Worksheet


Set sh2 = ThisWorkbook.Sheets(“Sheet2”)

shLR = sh2.Cells(Rows.Count, 1).End(xlUp).Row + 1

sh2.Cells(shLR, 1) = Date
sh2.Cells(shLR, 1) = Time
End Sub

b. Workbook Activate Event

Private Sub Workbook_Activate()


MsgBox "Welcome Back!"
End Sub

c. Workbook Before Save Event

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

answer = MsgBox("Are you sure you want to save?", vbYesNo)


If answer = vbNo Then
Cancel = True
End If

End Sub
P a g e | 22

d. Workbook After Save Event

Private Sub Workbook_AfterSave(ByVal Success As Boolean)


If Success = True Then
myVAR = "successful"
Else
myVAR = "unsuccessful"
End If
MsgBox "The save was " & myVAR
End Sub

e. Workbook Before Close Event

Private Sub Workbook_BeforeClose(Cancel As Boolean)


answer = MsgBox("Are you sure you want to close?", vbYesNo)
If answer = vbYes Then
Cancel = False
Else
Cancel = True
End If
End Sub

f. Workbook Before Print Event


Private Sub Workbook_BeforePrint(Cancel As Boolean)
Cancel = True
MsgBox "Bawal print, mahal ink, mahal papel, ikaw di mahal, gawa ka iyo spreadsheet tsaka
ka print!!"
End Sub

g. Workbook Deactivate Event


Private Sub Workbook_Deactivate()
MsgBox "Balik ka ha?, mamimiss kita!"
End Sub

h. Workbook New Sheet Event


Private Sub Workbook_NewSheet(ByVal Sh As Object)
application.displayalerts
MsgBox "You have a new sheet"
Sh.Cells.Font.Bold = True
End Sub

i. Workbook Sheet Activate Event


Private Sub Workbook_SheetActivate(ByVal Sh As Object)
P a g e | 23

If Sh.Name = "Sheet3" Then


Sheets("Sheet3").Visible = False
MsgBox "Uy nawala!"
End If
End Sub

j. Workbook Delete, Double Click, Event


Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Sheet3" Then
Sheets("Sheet3").Visible = False
MsgBox "Uy nawala!"
End If
End Sub
TOPIC 9 - STUDENT PROJECT

 -Make a Excel VBA program that will calculate the area of closed traverse after you
input the bearings and length of the lot. Limits (3-1000 bearings)

 -Need each button for Clearing of Data, Input of data, and Calculating the Area
P a g e | 24

ACTUAL CODES FOR THE PROJECT

A. CLEAR DATA CODES


Private Sub CommandButton1_Click()
Dim dsheet As Worksheet
Dim rptsheet As Worksheet

Set dsheet = ThisWorkbook.Sheets("data")


Set rptsheet = ThisWorkbook.Sheets("report")
dsheet.Range("Table_02").ClearContents

dsheet.Range("A1") = "BEARING"
dsheet.Range("B1") = "DISTANCE"

End Sub

B. INPUT DATA CODES


Private Sub CommandButton3_Click()
NUMBRNG = InputBox("How many bearings?")
For x = 1 To NUMBRNG
BRNG = InputBox("Input Bearing")
Cells(x + 1, 1) = BRNG
DSTNC = InputBox("Input Distance in meter")
Cells(x + 1, 2) = DSTNC
If BRNG = Empty Or DSTNC = Empty Then Exit Sub
Next x

End Sub
P a g e | 25

C. CALCULATE AREA CODES


Private Sub CommandButton2_Click()
Dim dsheet As Worksheet
Dim rptsheet As Worksheet

Set dsheet = ThisWorkbook.Sheets("data")


Set rptsheet = ThisWorkbook.Sheets("report")

Dim cell(1 To 3) As Range


Dim Text(1 To 3), formula As String

LastRow = dsheet.Cells(Rows.Count, 1).End(xlUp).Row


dsheet.Range("C1") = "UPPERCASE"
dsheet.Range("D1") = "TRIM"
dsheet.Range("E1") = "N/S"
dsheet.Range("F1") = "E/W"
dsheet.Range("G1") = "D"
dsheet.Range("H1") = "'"
dsheet.Range("I1") = """"
dsheet.Range("J1") = "DEGREE"
dsheet.Range("K1") = "MINUTE"
dsheet.Range("L1") = "SECOND"
dsheet.Range("M1") = "DECIMAL"
dsheet.Range("N1") = "AZIMUTH"
dsheet.Range("O1") = "LAT"
dsheet.Range("P1") = "DEP"
dsheet.Range("Q1") = "AD LAT"
dsheet.Range("R1") = "AD DEP"
dsheet.Range("S1") = "COR LAT"
dsheet.Range("T1") = "COR DEP"
dsheet.Range("U1") = "DMD"
dsheet.Range("V1") = "2A"
dsheet.Range("U2") = "=T2"
dsheet.Range("U" & LastRow + 1) = "2A"
dsheet.Range("U" & LastRow + 2) = "A"

dsheet.Cells.HorizontalAlignment = xlCenter

GoTo Line2
Line1:
Dim ErrorLot1 As Double
ErrorLot1 = Application.WorksheetFunction.Sum(Range("O2:O" &
LastRow))
Dim ErrorSumL1 As Double
ErrorSumL1 = Application.WorksheetFunction.SumIf(Range("O2:O" &
LastRow), ">0")
Dim ErrorSumL2 As Double
ErrorSumL2 = Application.WorksheetFunction.SumIf(Range("O2:O" &
LastRow), "<0")
Dim ErrorSumL As Double
P a g e | 26

ErrorSumL = Application.WorksheetFunction.Sum(Abs(ErrorSumL1) +
Abs(ErrorSumL2))
ErrorL = ErrorLot1 / ErrorSumL

Dim ErrorLot2 As Double


ErrorLot2 = Application.WorksheetFunction.Sum(Range("P2:P" &
LastRow))
Dim ErrorSumD1 As Double
ErrorSumD1 = Application.WorksheetFunction.SumIf(Range("P2:P" &
LastRow), ">0")
Dim ErrorSumD2 As Double
ErrorSumD2 = Application.WorksheetFunction.SumIf(Range("P2:P" &
LastRow), "<0")
Dim ErrorSumD As Double
ErrorSumD = Application.WorksheetFunction.Sum(Abs(ErrorSumD1) +
Abs(ErrorSumD2))
ErrorD = ErrorLot2 / ErrorSumD

GoTo Line3
Line2:
For x = 2 To LastRow

dsheet.Cells(x, 3).formula = "=upper(a:a)"


dsheet.Cells(x, 4).formula = "=Trim(c:c)"
If dsheet.Cells(x, 5) = "D" Then
dsheet.Cells(x, 5) = "=d:d"
Else
dsheet.Cells(x, 5).formula = "=left(d:d)"
End If

If dsheet.Cells(x, 6) = "H" Or dsheet.Cells(x, 6) = "T" Then


dsheet.Cells(x, 6) = "=d:d"
Else
dsheet.Cells(x, 6).formula = "=RIGHT(d:d)"
End If

If dsheet.Cells(x, 7) = "1" Then


dsheet.Cells(x, 7) = "=d:d"
Else
dsheet.Cells(x, 7) = "=iFERROR(Search(""d"",d:d),1)"
End If

If dsheet.Cells(x, 5) = "N" Or dsheet.Cells(x, 5) = "S" Then


dsheet.Cells(x, 8) = "=iferror(search(""'"",d:d),1)"
Else
dsheet.Cells(x, 8) = "=d:d"
End If
If dsheet.Cells(x, 5) = "N" Or dsheet.Cells(x, 5) = "S" Then
dsheet.Cells(x, 9) = "=iferror(search("""""""",d:d),1)"
Else
dsheet.Cells(x, 9) = "=d:d"
P a g e | 27

End If

If dsheet.Cells(x, 5) = "N" Or dsheet.Cells(x, 5) = "S" Then


dsheet.Cells(x, 10) = "=iferror(MID(d:d,2,(g:g)-2),0)"
Else
dsheet.Cells(x, 10) = "0"
End If

If dsheet.Cells(x, 5) = "N" Or dsheet.Cells(x, 5) = "S" Then


dsheet.Cells(x, 11) = "=iferror(MID(d:d,((g:g)+1),((h:h)-((g:g)+1))),0)"
Else
dsheet.Cells(x, 11) = "0"
End If

If dsheet.Cells(x, 5) = "N" Or dsheet.Cells(x, 5) = "S" Then


dsheet.Cells(x, 12) = "=iferror(MID(d:d,((h:h)+1),((i:i)-((h:h)+1))),0)"
Else
dsheet.Cells(x, 12) = "0"
End If

dsheet.Cells(x, 13).formula = "=j:j+(k:k/60)+(l:l/3600)"

If dsheet.Cells(x, 5) = "N" And dsheet.Cells(x, 6) = "E" Then


dsheet.Cells(x, 14) = "=M:M"
ElseIf dsheet.Cells(x, 5) = "N" And dsheet.Cells(x, 6) = "W" Then
dsheet.Cells(x, 14) = "=360-M:M"
ElseIf dsheet.Cells(x, 5) = "S" And dsheet.Cells(x, 6) = "E" Then
dsheet.Cells(x, 14) = "=180-M:M"
ElseIf dsheet.Cells(x, 5) = "S" And dsheet.Cells(x, 6) = "W" Then
dsheet.Cells(x, 14) = "=180+M:M"
ElseIf dsheet.Cells(x, 5) = "DUE NORTH" Then
dsheet.Cells(x, 14) = "0"
ElseIf dsheet.Cells(x, 5) = "DUE EAST" Then
dsheet.Cells(x, 14) = "90"
ElseIf dsheet.Cells(x, 5) = "DUE SOUTH" Then
dsheet.Cells(x, 14) = "180"
ElseIf dsheet.Cells(x, 5) = "DUE WEST" Then
dsheet.Cells(x, 14) = "270"
End If

dsheet.Cells(x, 15).formula = "=b:b*COS(RADIANS(N:N))"


dsheet.Cells(x, 16).formula = "=b:b*SIN(RADIANS(N:N))"
Next
GoTo Line1

Line3:
For x = 2 To LastRow
dsheet.Cells(x, 17).formula = "=ABS(O:O*" & ErrorL & ")"
dsheet.Cells(x, 18).formula = "=ABS(P:P*" & ErrorD & ")"
dsheet.Cells(x, 19).formula = "=O:O-Q:Q"
dsheet.Cells(x, 20).formula = "=P:P-R:R"
P a g e | 28

Text1 = "U" & x


Text2 = "T" & x
Text3 = "T" & x + 1
If x = LastRow Then
Else
dsheet.Cells(x + 1, 21).formula = "=" & Text1 & "+" & Text2 & "+" & Text3
End If
dsheet.Cells(x, 22).formula = "=U:U*S:S"

dsheet.Range("V" & LastRow + 1).formula = "=ABS(SUM(V2:V" & LastRow


& "))"
dsheet.Range("V" & LastRow + 2).formula = "=V" & LastRow + 1 & "/2"
Next
MsgBox "Total Area: " & dsheet.Range("V" & LastRow + 2) & " sq.m"

End Sub

You might also like