This commit is contained in:
louiscklaw
2025-02-01 02:02:37 +08:00
commit 1b62961605
248 changed files with 11997 additions and 0 deletions

31
.gitattributes vendored Normal file
View File

@@ -0,0 +1,31 @@
*.mp4 filter=lfs diff=lfs merge=lfs
*.zip filter=lfs diff=lfs merge=lfs
*.7z filter=lfs diff=lfs merge=lfs
*.tar.gz filter=lfs diff=lfs merge=lfs
*.jpg filter=lfs diff=lfs merge=lfs
*.png filter=lfs diff=lfs merge=lfs
*.avif filter=lfs diff=lfs merge=lfs
*.webm filter=lfs diff=lfs merge=lfs
*.mkv filter=lfs diff=lfs merge=lfs
# Documents
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.gif filter=lfs diff=lfs merge=lfs
*.GIF filter=lfs diff=lfs merge=lfs
*.bmp filter=lfs diff=lfs merge=lfs
*.BMP filter=lfs diff=lfs merge=lfs
*.tiff filter=lfs diff=lfs merge=lfs
*.TIFF filter=lfs diff=lfs merge=lfs
*.wav filter=lfs diff=lfs merge=lfs
*.WAV filter=lfs diff=lfs merge=lfs
*.log filter=lfs diff=lfs merge=lfs

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
**/~*.*

1
backup.bat Normal file
View File

@@ -0,0 +1 @@
node ./backup.js

63
backup.js Normal file
View File

@@ -0,0 +1,63 @@
const execSync = require("child_process").execSync;
const fs = require("fs");
const path = require("path");
// Function to get all subdirectories of a given directory
function getDirectories(srcPath, excludeDirs) {
return fs
.readdirSync(srcPath)
.filter(
(file) =>
!excludeDirs.includes(file) &&
fs.lstatSync(path.join(srcPath, file)).isDirectory()
)
.map((name) => path.join(srcPath, name));
}
// Get current working directory
const cwd = process.cwd();
// Path to app-head directory
const appHeadDir = path.join(cwd, "task4");
// Check if app-head exists
if (!fs.existsSync(appHeadDir)) {
console.error(`Error: ${appHeadDir} does not exist.`);
process.exit(1);
}
// Execute reset.bat scripts
try {
// execSync(`cmd /c "cd ${appHeadDir} && scripts\\reset.bat"`, { stdio: 'inherit' });
} catch (err) {
console.error(`Error executing reset.bat script: ${err.message}`);
process.exit(1);
}
// Define excluded directories
const excludedDirs = [".next", "node_modules", ".git", "volumes", "_mp4"];
// Copy app-head directory and its contents to a new directory with an increasing number suffix
let maxNum = 0;
const directories = getDirectories(cwd, excludedDirs);
for (const dir of directories) {
const match = dir.match(/^.+draft(\d+)$/);
if (match) {
const num = parseInt(match[1], 10);
if (num > maxNum) {
maxNum = num;
}
}
}
var zerofilled = ("0000" + (maxNum + 1)).slice(-4);
const targetDir = path.join(cwd, `draft${zerofilled}`);
fs.mkdirSync(targetDir);
// Copy app-head directory and its contents to targetDir, excluding specified directories
fs.cpSync(appHeadDir, targetDir, {
filter: (src) => !excludedDirs.includes(path.basename(src)),
recursive: true,
});
console.log(`Successfully copied ${appHeadDir} to ${targetDir}.`);

7
gitUpdate.bat Normal file
View File

@@ -0,0 +1,7 @@
git status .
@pause
git add .
git commit -m"update jimmycheung93,"
start git push

16
gitUpdate.sh Executable file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -ex
git config --global http.version HTTP/1.1
git config --global lfs.allowincompletepush true
git config --global lfs.locksverify true
git config --global http.postBuffer 5368709120
git add .
git commit -m 'update,'
git push
echo "done"

9
history.md Normal file
View File

@@ -0,0 +1,9 @@
# history
### task 1
- HKD 200
### task 2
- HKD 250

13
meta.md Normal file
View File

@@ -0,0 +1,13 @@
---
tags: [vba, excel]
---
# jimmycheung93
### task 1
- HKD 200
### task 2
- HKD 250

13
package.json Normal file
View File

@@ -0,0 +1,13 @@
{
"name": "task1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"gitUpdate": "git add . ; git commit -m\"update jimmycheung93,\""
},
"keywords": [],
"author": "",
"license": "ISC"
}

BIN
task1/Assignment1_2023B.pdf Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

BIN
task3/Assignment1.pdf Normal file

Binary file not shown.

BIN
task3/Lecture+2.pdf Normal file

Binary file not shown.

BIN
task3/Lecture+3.pdf Normal file

Binary file not shown.

BIN
task3/Lecture+4.pdf Normal file

Binary file not shown.

BIN
task3/Lecture+5.pdf Normal file

Binary file not shown.

BIN
task3/Lecture+6.pdf Normal file

Binary file not shown.

BIN
task3/Lecture+7.pdf Normal file

Binary file not shown.

Binary file not shown.

0
task3/notes.md Normal file
View File

12
task3/package.json Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "task3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"gitUpdate": "git add . && git commit -m\"update task3,\""
},
"keywords": [],
"author": "",
"license": "ISC"
}

Binary file not shown.

412
task4/1/APAnalysis.bas Normal file
View File

@@ -0,0 +1,412 @@
Attribute VB_Name = "APAnalysis"
Option Explicit
Function APAnalysis_Calc(ByVal TablesMeta As Variant) As Variant
Dim agent_sales_table As Variant
Dim product_sales_meta As Variant
Dim product_sales_table As Variant
Dim agent_working_performance As Variant
Dim i, j, k, m, intMonth, intQuarter As Integer
Dim ps As Integer
Dim val_product_sales_date As String
Dim sales_name As Variant
Dim dt As String
Dim monthly_top_5_comission_details(12, 5, 10) As Double
Dim monthly_top_5_comission_value(12, 5) As Double
Dim monthly_top_5_comission_name(12, 5) As String
agent_sales_table = TablesMeta(0)
Dim agent_sales_table_rows As Variant
agent_sales_table_rows = agent_sales_table(0)
product_sales_table = TablesMeta(1)
Dim product_sales_table_row As Variant
product_sales_table_row = product_sales_table(0)
agent_working_performance = TablesMeta(2)
Dim val_product_sales_comission As String
Dim val_product_sales_selling_price As String
Dim val_product_sales_selling_unit As String
Dim val_agent_sale_commision_pct As String
Dim val_agent_sale_agent_name As String
Dim val_agent_sale_agent_team As String
Dim monthly_total(12) As Double
Dim monthly_total_TA(12) As Double ' team a
Dim monthly_total_TB(12) As Double ' team b
Dim monthly_commission(12) As Double
Dim montyly_commission_TA(12) As Double ' team a
Dim montyly_commission_TB(12) As Double ' team b
Dim quartely_commission_TA(12) As Double ' team a
Dim quartely_commission_TB(12) As Double ' team b
For j = 1 To 12
monthly_total(j) = 0
monthly_total_TA(j) = 0
monthly_total_TB(j) = 0
Next j
For ps = 1 To product_sales_table(1)
val_product_sales_date = product_sales_table_row(ps, 2)
dt = DateValue(val_product_sales_date)
intMonth = month(dt)
intQuarter = Int((intMonth - 1) / 3) + 1
val_product_sales_selling_unit = product_sales_table_row(ps, 4)
val_product_sales_selling_price = product_sales_table_row(ps, 5)
val_agent_sale_agent_name = agent_sales_table_rows(ps, 3)
val_agent_sale_agent_team = agent_sales_table_rows(ps, 4)
val_agent_sale_commision_pct = agent_sales_table_rows(ps, 6)
val_product_sales_comission = (val_product_sales_selling_unit * val_product_sales_selling_price) * val_agent_sale_commision_pct
product_sales_table_row(ps, 6) = val_product_sales_comission
Dim temp_key As String
temp_key = val_agent_sale_agent_name + "," + CStr(intMonth)
' initialize per agent result
If (Not (IsEmpty(temp_key)) And Not (monthly_commission_per_agent.exists(temp_key))) Then
For j = 1 To 12
Var.monthly_commission_per_agent(val_agent_sale_agent_name + "," + CStr(j)) = 0
Var.monthly_product_sales_selling_unit_per_agent(val_agent_sale_agent_name + "," + CStr(j)) = 0
Var.monthly_product_sales_selling_price_per_agent(val_agent_sale_agent_name + "," + CStr(j)) = 0
Var.monthly_product_sales_per_agent(val_agent_sale_agent_name + "," + CStr(j)) = 0
Next j
End If
monthly_total(intMonth) = monthly_total(intMonth) + (val_product_sales_selling_unit * val_product_sales_selling_price)
monthly_commission_per_agent(temp_key) = monthly_commission_per_agent(temp_key) + val_product_sales_comission
Var.monthly_product_sales_selling_unit_per_agent(temp_key) = Var.monthly_product_sales_selling_unit_per_agent(temp_key) + val_product_sales_selling_unit
Var.monthly_product_sales_selling_price_per_agent(temp_key) = Var.monthly_product_sales_selling_price_per_agent(temp_key) + val_product_sales_selling_price
Var.monthly_product_sales_per_agent(temp_key) = Var.monthly_product_sales_per_agent(temp_key) + val_product_sales_selling_price
monthly_commission(intMonth) = monthly_commission(intMonth) + val_product_sales_comission
If (val_agent_sale_agent_team = "A") Then
montyly_commission_TA(intMonth) = montyly_commission_TA(intMonth) + val_product_sales_comission
End If
If (val_agent_sale_agent_team = "B") Then
montyly_commission_TB(intMonth) = montyly_commission_TB(intMonth) + val_product_sales_comission
End If
If (val_agent_sale_agent_team = "A") Then
quartely_commission_TA(intQuarter) = quartely_commission_TA(intQuarter) + val_product_sales_comission
End If
If (val_agent_sale_agent_team = "B") Then
quartely_commission_TB(intQuarter) = quartely_commission_TB(intQuarter) + val_product_sales_comission
End If
Next ps
For m = 1 To 12
Dim temp_sort(20) As Double
i = 0
For Each sales_name In SALES_ARRAY
temp_key = sales_name + "," + CStr(m)
temp_sort(i) = monthly_commission_per_agent(temp_key)
i = i + 1
Next sales_name
sort_result = SortArray(temp_sort)
monthly_top_5_comission_value(m, 0) = sort_result(0)
monthly_top_5_comission_value(m, 1) = sort_result(1)
monthly_top_5_comission_value(m, 2) = sort_result(2)
monthly_top_5_comission_value(m, 3) = sort_result(3)
monthly_top_5_comission_value(m, 4) = sort_result(4)
For Each sales_name In SALES_ARRAY
temp_key = sales_name + "," + CStr(m)
If (monthly_top_5_comission_value(m, 0) = monthly_commission_per_agent(temp_key)) Then
monthly_top_5_comission_name(m, 0) = sales_name
End If
If (monthly_top_5_comission_value(m, 1) = monthly_commission_per_agent(temp_key)) Then
monthly_top_5_comission_name(m, 1) = sales_name
End If
If (monthly_top_5_comission_value(m, 2) = monthly_commission_per_agent(temp_key)) Then
monthly_top_5_comission_name(m, 2) = sales_name
End If
If (monthly_top_5_comission_value(m, 3) = monthly_commission_per_agent(temp_key)) Then
monthly_top_5_comission_name(m, 3) = sales_name
End If
If (monthly_top_5_comission_value(m, 4) = monthly_commission_per_agent(temp_key)) Then
monthly_top_5_comission_name(m, 4) = sales_name
End If
Next sales_name
Next m
APAnalysis_Calc = Array( _
monthly_commission_per_agent, _
monthly_commission, _
montyly_commission_TA, _
montyly_commission_TB, _
quartely_commission_TA, _
quartely_commission_TB, _
monthly_top_5_comission_name, _
monthly_top_5_comission_value, _
monthly_total, _
monthly_total_TA, _
monthly_total_TB)
Debug.Print "calc done"
End Function
Function APAnalysis_WriteTable(ByVal calc_result As Variant, ByVal file_path As String, ByRef wb As Workbook)
Dim monthly_commission As Variant
Dim montyly_commission_TA As Variant ' team a
Dim montyly_commission_TB As Variant ' team b
Dim quartely_commission_TA As Variant ' team a
Dim quartely_commission_TB As Variant ' team b
Dim monthly_top_5_comission_name As Variant
Dim monthly_top_5_comission_value As Variant
Dim range_need_merge, ranges_need_merge As Variant
Dim ranges_need_paint As Variant
Dim i, j, k, m, r, intMonth, intQuarter As Integer
Dim sale_name_comma_month As String
monthly_commission = calc_result(1)
montyly_commission_TA = calc_result(2) ' team a
montyly_commission_TB = calc_result(3) ' team b
quartely_commission_TA = calc_result(4) ' team a
quartely_commission_TB = calc_result(5) ' team b
monthly_top_5_comission_name = calc_result(6)
monthly_top_5_comission_value = calc_result(7)
Const TOP_ROW As Long = 1
Const START_CELL As String = "A2"
Dim ws As Worksheet
Dim startCell As Range
Dim tempArray() As Variant
' Check if the sheet exists
On Error Resume Next
Set ws = wb.Sheets("Agent performance analysis")
On Error GoTo 0
' If not found, create a new sheet
If ws Is Nothing Then
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = "Agent performance analysis"
Else
' Empty the entire sheet
ws.UsedRange.ClearContents
End If
' Write month names
Set startCell = ws.Range("B1")
tempArray = Array("January", "Feburary", "March", "April", "May", "June", "July", "Augest", "September", "October", "November", "December")
For i = LBound(tempArray) To UBound(tempArray)
startCell.Offset(0, i).Value = tempArray(i)
Next i
' Write month names
Set startCell = ws.Range("A2")
For i = LBound(SALES_ARRAY) To UBound(SALES_ARRAY)
startCell.Offset(i, 0).Value = SALES_ARRAY(i)
Next i
' Write month names
Set startCell = ws.Range("A14")
tempArray = Array("Total", "", "Team A total", "Team B Total", "Team A Quartely", "Team B Quartely")
For i = LBound(tempArray) To UBound(tempArray)
startCell.Offset(i, 0).Value = tempArray(i)
Next i
Set startCell = ws.Range("B2")
For m = 1 To 12
For i = LBound(SALES_ARRAY) To UBound(SALES_ARRAY)
Dim sales_name As String
sale_name_comma_month = SALES_ARRAY(i) + "," + CStr(m)
startCell.Offset(i, m - 1).Value = monthly_commission_per_agent(sale_name_comma_month)
Next i
Next m
' Write month names
Set startCell = ws.Range("B14")
tempArray = Array("Total", "", "Team A total", "Team B Total", "Team A Quartely", "Team B Quartely")
' For i = LBound(tempArray) To UBound(tempArray)
' startCell.Offset(i, 0).Value = tempArray(i)
' Next i
For m = 1 To 12
intQuarter = Common.GetQuarterFromMonth(m)
startCell.Offset(0, m - 1).Value = monthly_commission(m)
startCell.Offset(2, m - 1).Value = montyly_commission_TA(m)
startCell.Offset(3, m - 1).Value = montyly_commission_TB(m)
startCell.Offset(4, m - 1).Value = quartely_commission_TA(intQuarter)
startCell.Offset(5, m - 1).Value = quartely_commission_TB(intQuarter)
Next m
' styling
For i = 0 To 100
ws.Range("A1").Offset(0, i).EntireColumn.AutoFit
Next i
For i = 1 To 14
Range("A1").Offset(0, i).EntireColumn.ColumnWidth = 15
Next i
ranges_need_merge = Array("B18:D18", "E18:G18", "H18:J18", "K18:M18", "B19:D19", "E19:G19", "H19:J19", "K19:M19")
For r = LBound(ranges_need_merge) To UBound(ranges_need_merge)
range_need_merge = ranges_need_merge(r)
With Range(range_need_merge)
.Merge
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
End With
Next r
ranges_need_paint = Array("B1:M1")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(217, 210, 233)
End With
Next r
ranges_need_paint = Array("A2:A11", "A14")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(180, 167, 214)
End With
Next r
ranges_need_paint = Array("A16:A19")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(142, 124, 195)
End With
Next r
' Rank for each month
Set startCell = ws.Range("A21")
startCell.Value = "Rank for each month"
tempArray = Array("January", "Feburary", "March", "April", "May", "June")
For i = 0 To 5
startCell.Offset(1, (i * 2) + 1).Value = tempArray(i)
Next i
For i = 1 To 5
startCell.Offset(i + 1, 0).Value = i
Next i
tempArray = Array("July", "Augest", "September", "October", "November", "December")
For i = 0 To 5
startCell.Offset(8, (i * 2) + 1).Value = tempArray(i)
Next i
For i = 1 To 5
startCell.Offset(i + 8, 0).Value = i
Next i
For m = 1 To 6
i = m - 1
startCell.Offset(2, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 0)
startCell.Offset(3, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 1)
startCell.Offset(4, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 2)
startCell.Offset(5, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 3)
startCell.Offset(6, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 4)
startCell.Offset(2, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 0)
startCell.Offset(3, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 1)
startCell.Offset(4, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 2)
startCell.Offset(5, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 3)
startCell.Offset(6, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 4)
Next m
For m = 7 To 12
i = m - 7
startCell.Offset(9, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 0)
startCell.Offset(10, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 1)
startCell.Offset(11, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 2)
startCell.Offset(12, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 3)
startCell.Offset(13, (i * 2) + 1).Value = monthly_top_5_comission_name(m, 4)
startCell.Offset(9, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 0)
startCell.Offset(10, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 1)
startCell.Offset(11, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 2)
startCell.Offset(12, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 3)
startCell.Offset(13, (i * 2) + 2).Value = monthly_top_5_comission_value(m, 4)
Next m
' styling
For i = 0 To 100
ws.Range("A1").Offset(0, i).EntireColumn.AutoFit
Next i
For i = 1 To 14
Range("A1").Offset(0, i).EntireColumn.ColumnWidth = 15
Next i
ranges_need_merge = Array("B22:C22", "D22:E22", "F22:G22", "H22:I22", "J22:k22", "L22:M22", "B29:C29", "D29:E29", "F29:G29", "H29:I29", "J29:k29", "L29:M29")
For r = LBound(ranges_need_merge) To UBound(ranges_need_merge)
range_need_merge = ranges_need_merge(r)
With Range(range_need_merge)
.Merge
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
End With
Next r
ranges_need_paint = Array("B22:C22", "D22:E22", "F22:G22", "H22:I22", "J22:k22", "L22:M22", "B29:C29", "D29:E29", "F29:G29", "H29:I29", "J29:k29", "L29:M29")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(234, 209, 220)
End With
Next r
ranges_need_paint = Array("A21", "A23", "A25", "A27", "A30", "A32", "A34")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(234, 209, 220)
End With
Next r
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function

237
task4/1/APAnalysisGraph.bas Normal file
View File

@@ -0,0 +1,237 @@
Attribute VB_Name = "APAnalysisGraph"
Function TeamATotalSalesCommisionPerformanceTable(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim monthly_commission As Variant
Dim montyly_commission_TA As Variant ' team a
monthly_commission = calc_result(1)
montyly_commission_TA = calc_result(2) ' team a
Dim monthNames() As Variant
monthNames = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Agent performance analysis")
' Write headers
Set startCell = ws.Range("A1")
startCell.Value = "Team A Total Sales Commision Performance"
startCell.Offset(1, 0).Value = "Month"
startCell.Offset(1, 1).Value = "Amount"
Set startCell = ws.Range("A3")
For m = LBound(monthNames) To UBound(monthNames)
startCell.Offset(m, 0).Value = monthNames(m)
startCell.Offset(m, 1).Value = montyly_commission_TA(m + 1)
Next m
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function
Function TeamBTotalSalesCommisionPerformanceTable(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim monthly_commission As Variant
Dim montyly_commission_TB As Variant ' team b
monthly_commission = calc_result(1)
montyly_commission_TB = calc_result(3) ' team b
Dim monthNames() As Variant
monthNames = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Agent performance analysis")
' Write headers
Set startCell = ws.Range("A20")
startCell.Value = "Team B Total Sales Commision Performance"
startCell.Offset(1, 0).Value = "Month"
startCell.Offset(1, 1).Value = "Amount"
Set startCell = ws.Range("A22")
For m = LBound(monthNames) To UBound(monthNames)
startCell.Offset(m, 0).Value = monthNames(m)
startCell.Offset(m, 1).Value = montyly_commission_TB(m + 1)
Next m
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function
Function TeamATotalSalesCommisionPerformanceGraph(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Agent performance analysis")
Dim cht As Chart
Dim ax As Axis
' insert graph
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
cht.SetSourceData Source:=Range("A2:B14")
' update chart styling
cht.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Month"
cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
cht.ChartTitle.Text = "Team A total Sales commision performance"
Set ax = cht.Axes(xlValue, xlPrimary)
ax.HasTitle = True
ax.AxisTitle.Format.TextFrame2.TextRange.Characters.Text = "Amount"
cho.Top = 0
cho.Left = 0
cho.Width = 400
cho.Height = 300
End Function
Function TeamBTotalSalesCommisionPerformanceGraph(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Agent performance analysis")
Dim cht As Chart
Dim ax As Axis
' insert graph
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
cht.SetSourceData Source:=Range("A21:B33")
' update chart styling
cht.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Month"
cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
cht.ChartTitle.Text = "Team B total Sales commision performance"
Set ax = cht.Axes(xlValue, xlPrimary)
ax.HasTitle = True
ax.AxisTitle.Format.TextFrame2.TextRange.Characters.Text = "Amount"
cho.Top = 300
cho.Left = 0
cho.Width = 400
cho.Height = 300
End Function
Function RankOfAgentSalesCommMonthlyTable(ByVal calc_result As Variant, ByVal file_path As String)
Const HEADER_ROW As Long = 1
Const START_CELL As String = "F1"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim monthly_top_5_comission_name As Variant
Dim monthly_top_5_comission_value As Variant
monthly_top_5_comission_name = calc_result(6)
monthly_top_5_comission_value = calc_result(7)
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Agent performance analysis")
' Write headers
Set startCell = ws.Range(START_CELL)
startCell.Offset(0, 0).Value = "Top 5 Agent's Commssion"
'generate graph by month
For m = LBound(MONTH_NAMES) To UBound(MONTH_NAMES)
startCell.Offset(1, 0 + (m * 3)).Value = "Name"
startCell.Offset(1, 1 + (m * 3)).Value = "Commssion"
startCell.Offset(1 + 1, 0 + (m * 3)).Value = monthly_top_5_comission_name(m + 1, 0)
startCell.Offset(1 + 2, 0 + (m * 3)).Value = monthly_top_5_comission_name(m + 1, 1)
startCell.Offset(1 + 3, 0 + (m * 3)).Value = monthly_top_5_comission_name(m + 1, 2)
startCell.Offset(1 + 4, 0 + (m * 3)).Value = monthly_top_5_comission_name(m + 1, 3)
startCell.Offset(1 + 5, 0 + (m * 3)).Value = monthly_top_5_comission_name(m + 1, 4)
startCell.Offset(1 + 1, 1 + (m * 3)).Value = monthly_top_5_comission_value(m + 1, 0)
startCell.Offset(1 + 2, 1 + (m * 3)).Value = monthly_top_5_comission_value(m + 1, 1)
startCell.Offset(1 + 3, 1 + (m * 3)).Value = monthly_top_5_comission_value(m + 1, 2)
startCell.Offset(1 + 4, 1 + (m * 3)).Value = monthly_top_5_comission_value(m + 1, 3)
startCell.Offset(1 + 5, 1 + (m * 3)).Value = monthly_top_5_comission_value(m + 1, 4)
Next m
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function
Function RankOfAgentSalesCommMonthlyGraph(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Agent performance analysis")
Dim DATA_RANGES As Variant
DATA_RANGES = Array("F2:G7", "I2:J7", "L2:M7", "O2:P7", "R2:S7", "U2:V7", "X2:Y7", "AA2:AB7", "AD2:AE7", "AG2:AH7", "AJ2:AK7", "AM2:AN7")
Dim GRAPH_TOPS As Variant
Dim GRAPH_LEFTS As Variant
GRAPH_TOPS = Array(0, 0, 0, 200, 200, 200, 400, 400, 400, 600, 600, 600)
GRAPH_LEFTS = Array(400, 700, 1000, 400, 700, 1000, 400, 700, 1000, 400, 700, 1000)
'generate graph by month
For m = LBound(MONTH_NAMES) To UBound(MONTH_NAMES)
month_name = MONTH_NAMES(m)
' insert graph
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
ActiveChart.SetSourceData Source:=Range(DATA_RANGES(m))
ActiveChart.ChartTitle.Text = "Top 5 Sales Commission " & month_name
' update chart styling
cht.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Name"
cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
Set ax = cht.Axes(xlValue, xlPrimary)
ax.HasTitle = True
ax.AxisTitle.Format.TextFrame2.TextRange.Characters.Text = "Commission"
cho.Top = GRAPH_TOPS(m)
cho.Left = GRAPH_LEFTS(m)
cho.Width = 300
cho.Height = 200
Next m
End Function
Function Helloworld()
Debug.Print "helloworld Sales_Analysis_Product_Category"
End Function

View File

@@ -0,0 +1,25 @@
Attribute VB_Name = "APAnalysis_Sales_Calc"
Option Explicit
Function Run(ByVal TablesMeta As Variant)
' agent_working_performance
Dim agent_working_performance As Variant
Dim awp_rows As Variant
Dim awp_lastrow As Integer
Dim awp_current_row As Integer
' init agent_working_performance
agent_working_performance = TablesMeta(2)
awp_rows = agent_working_performance(0)
awp_lastrow = CInt(agent_working_performance(1))
awp_current_row = 0
For awp_current_row = 1 To 4
Debug.Print (awp_rows(1, 1))
Next awp_current_row
Run = "done"
End Function

View File

@@ -0,0 +1,191 @@
Attribute VB_Name = "AgentWorkingPerformancePivot"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim SalesNewCaseByMonth As Integer
Dim SalesCollapsedCaseByMonth As Integer
Dim i, j As Integer
' variable for result
Dim agent_month_new_case
Set agent_month_new_case = CreateObject("Scripting.Dictionary")
Dim agent_month_collapsed_case
Set agent_month_collapsed_case = CreateObject("Scripting.Dictionary")
Dim agent_quarter_new_case
Set agent_quarter_new_case = CreateObject("Scripting.Dictionary")
Dim agent_quarter_collapsed_case
Set agent_quarter_collapsed_case = CreateObject("Scripting.Dictionary")
For i = start_row To last_row
Dim date_value As String
Dim month, quarter As Integer
Dim agent_name, new_case, collapsed_case As String
Dim agent_quarter_key, temp_key As String
date_value = ReadCellValue("A" & CStr(i))
month = GetMonthFrDate(date_value)
quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("B" & CStr(i))
new_case = ReadCellValue("D" & CStr(i))
collapsed_case = ReadCellValue("E" & CStr(i))
temp_key = agent_name + "," + CStr(month)
agent_quarter_key = agent_name + "," + CStr(quarter)
' create if not found agent_name
If (Not (IsEmpty(temp_key)) And Not (agent_month_new_case.exists(temp_key))) Then
For j = 1 To 12
agent_month_new_case(agent_name + "," + CStr(j)) = 0
agent_month_collapsed_case(agent_name + "," + CStr(j)) = 0
Next j
For j = 1 To 4
agent_quarter_new_case(agent_name + "," + CStr(j)) = 0
agent_quarter_collapsed_case(agent_name + "," + CStr(j)) = 0
Next j
End If
If (new_case <> "") Then
agent_month_new_case(temp_key) = agent_month_new_case(temp_key) + CInt(new_case)
End If
If (collapsed_case <> "") Then
agent_month_collapsed_case(temp_key) = agent_month_collapsed_case(temp_key) + CInt(collapsed_case)
End If
If (new_case <> "") Then
agent_quarter_new_case(agent_quarter_key) = agent_quarter_new_case(agent_quarter_key) + CInt(new_case)
End If
If (collapsed_case <> "") Then
agent_quarter_collapsed_case(agent_quarter_key) = agent_quarter_collapsed_case(agent_quarter_key) + CInt(collapsed_case)
End If
Next i
' sales_index
' sales_month_new_case
' sales_month_collapsed_case
' sales_quarter_new_case
' sales_quarter_collapsed_case
CountFigures = Array(agent_month_new_case, agent_month_collapsed_case, agent_quarter_new_case, agent_quarter_collapsed_case)
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function Run(ws As Worksheet)
' Dim ws As Worksheet
' Set ws = ThisWorkbook.Sheets("Sheet1")
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
count_figures_result = CountFigures(ws, start_row, last_row)
Dim agent_month_new_case, agent_month_collapsed_case
Dim agent_quarter_new_case, agent_quarter_collapsed_case
Set agent_month_new_case = count_figures_result(0)
Set agent_month_collapsed_case = count_figures_result(1)
Set agent_quarter_new_case = count_figures_result(2)
Set agent_quarter_collapsed_case = count_figures_result(3)
Debug.Print agent_month_new_case("Candy,1")
Run = count_figures_result
Debug.Print "done"
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Helloworld()
Debug.Print "helloworld"
End Sub

View File

@@ -0,0 +1,194 @@
Attribute VB_Name = "BestSalesEachMonth"
Option Explicit
Sub Helloworld()
Debug.Print "helloworld"
End Sub
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim SalesNewCaseByMonth As Integer
Dim SalesCollapsedCaseByMonth As Integer
Dim i, j As Integer
' variable for result
Dim monthly_total_sell, month_total_commission
Set monthly_total_sell = CreateObject("Scripting.Dictionary")
Set month_total_commission = CreateObject("Scripting.Dictionary")
Dim team_a_best, team_a_best_value, team_a_best_name, team_a_best_commission
Set team_a_best = CreateObject("Scripting.Dictionary")
Set team_a_best_value = CreateObject("Scripting.Dictionary")
Set team_a_best_name = CreateObject("Scripting.Dictionary")
Set team_a_best_commission = CreateObject("Scripting.Dictionary")
Dim team_b_best, team_b_best_value, team_b_best_name, team_b_best_commission
Set team_b_best = CreateObject("Scripting.Dictionary")
Set team_b_best_value = CreateObject("Scripting.Dictionary")
Set team_b_best_name = CreateObject("Scripting.Dictionary")
Set team_b_best_commission = CreateObject("Scripting.Dictionary")
For j = 1 To 12
team_a_best(CStr(j)) = 0
team_b_best(CStr(j)) = 0
Next j
For i = start_row To last_row
Dim date_value As String
Dim agent_name As String
Dim team As String
Dim temp_key As String
Dim selling_price, commision_pct, commision_value As Double
Dim int_month, int_quarter As Integer
date_value = ReadCellValue("B" & CStr(i))
int_month = GetMonthFrDate(date_value)
int_quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("C" & CStr(i))
team = ReadCellValue("D" & CStr(i))
selling_price = CDbl(ReadCellValue("E" & CStr(i)))
commision_pct = CDbl(ReadCellValue("F" & CStr(i)))
commision_value = selling_price * commision_pct
temp_key = agent_name & "," & int_month
' create if not found agent_name
If (Not (IsEmpty(temp_key)) And Not (monthly_total_sell.exists(temp_key))) Then
For j = 1 To 12
monthly_total_sell(agent_name + "," + CStr(j)) = 0
Next j
End If
monthly_total_sell(agent_name + "," + CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month)) + selling_price
month_total_commission(agent_name + "," + CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month)) + commision_value
' is in team A?
If (CheckSalesIsInTeamA(agent_name)) Then
If (monthly_total_sell(agent_name + "," + CStr(int_month)) > team_a_best(CStr(int_month))) Then
team_a_best_name(CStr(int_month)) = agent_name
team_a_best_value(CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month))
team_a_best_commission(CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month))
End If
End If
' is in team B?
If (CheckSalesIsInTeamB(agent_name)) Then
If (monthly_total_sell(agent_name + "," + CStr(int_month)) > team_b_best(CStr(int_month))) Then
team_b_best_name(CStr(int_month)) = agent_name
team_b_best_value(CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month))
team_b_best_commission(CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month))
End If
End If
Next i
CountFigures = Array(monthly_total_sell, _
team_a_best_name, _
team_a_best_value, _
team_a_best_commission, _
team_b_best_name, _
team_b_best_value, _
team_b_best_commission _
)
End Function
Function Run(ws As Worksheet)
'Dim ws As Worksheet
'Set ws = ThisWorkbook.Sheets("Sheet1")
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
count_figures_result = CountFigures(ws, start_row, last_row)
Run = count_figures_result
Debug.Print "done"
End Function
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = BestSalesEachMonth.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function

View File

@@ -0,0 +1,127 @@
Attribute VB_Name = "CasePersistencyGraph"
Function TeamACaseDistributionTable(ByVal calc_result As Variant, ByVal file_path As String)
Const HEADER_ROW As Long = 1
Const START_CELL As String = "A1"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim case_team_a_meta As Variant
Dim case_team_b_meta As Variant
case_team_a_meta = calc_result(5)
case_team_b_meta = calc_result(6)
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Case persistency")
' Write headers
Set startCell = ws.Range(START_CELL)
startCell.Value = "Team A Case Distribution"
startCell.Offset(1, 0).Value = "State"
startCell.Offset(1, 1).Value = "Case"
startCell.Offset(1 + 1, 0).Value = "Collapse"
startCell.Offset(1 + 2, 0).Value = "New Case"
startCell.Offset(1 + 1, 1).Value = case_team_a_meta(0)
startCell.Offset(1 + 2, 1).Value = case_team_a_meta(1)
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function
Function TeamACaseDistributionGraph(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Case persistency")
' insert graph
ActiveSheet.Shapes.AddChart2(251, xlPie).Select
ActiveChart.SetSourceData Source:=Range("$A$2:$B$4")
ActiveChart.SetElement (msoElementLegendNone)
ActiveChart.SetElement (msoElementDataLabelCallout)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Team A case Distribution"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Team A case Distribution"
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
cho.Top = 0
cho.Left = 0
cho.Width = 400
cho.Height = 300
End Function
Function TeamBCaseDistributionTable(ByVal calc_result As Variant, ByVal file_path As String)
Const HEADER_ROW As Long = 1
Const START_CELL As String = "F1"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim case_team_a_meta As Variant
Dim case_team_b_meta As Variant
case_team_a_meta = calc_result(5)
case_team_b_meta = calc_result(6)
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Case persistency")
' Write headers
Set startCell = ws.Range(START_CELL)
startCell.Value = "Team B Case Distribution"
startCell.Offset(1, 0).Value = "State"
startCell.Offset(1, 1).Value = "Case"
startCell.Offset(1 + 1, 0).Value = "Collapse"
startCell.Offset(1 + 2, 0).Value = "New Case"
startCell.Offset(1 + 1, 1).Value = case_team_b_meta(0)
startCell.Offset(1 + 2, 1).Value = case_team_b_meta(1)
End Function
Function TeamBCaseDistributionGraph(ByVal calc_result As Variant, ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Case persistency")
' insert graph
ActiveSheet.Shapes.AddChart2(251, xlPie).Select
ActiveChart.SetSourceData Source:=Range("F2:G4")
ActiveChart.SetElement (msoElementLegendNone)
ActiveChart.SetElement (msoElementDataLabelCallout)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Team B case Distribution"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Team B case Distribution"
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
cho.Top = 0
cho.Left = 400
cho.Width = 400
cho.Height = 300
End Function
Function Helloworld()
Debug.Print "helloworld CasePersistency"
End Function

326
task4/1/Common.bas Normal file
View File

@@ -0,0 +1,326 @@
Attribute VB_Name = "Common"
Option Explicit
' get row number for a given username
Function GetIdxByUsername(username As String) As Integer
Dim result_idx As Integer
Dim i As Integer
result_idx = -1
For i = 1 To Var.MAX_NUM_OF_SALES
If (username = usernames(i)) Then
result_idx = i
Exit For
End If
Next i
GetIdxByUsername = result_idx
End Function
' get age from account sheet for a given username
Function LookupAge(username As String) As String
Dim lookup_result As String
Dim i As Integer
For i = 1 To Var.MAX_NUM_OF_SALES
If (username = usernames(i)) Then
lookup_result = ages(i)
Exit For
End If
Next i
LookupAge = lookup_result
End Function
' get team from account sheet for a given username
Function LookupTeam(username As String) As String
Dim lookup_result As String
Dim i As Integer
For i = 1 To Var.MAX_NUM_OF_SALES
If (username = usernames(i)) Then
lookup_result = teams(i)
Exit For
End If
Next i
LookupTeam = lookup_result
End Function
Sub GenTextReport()
Dim sPath As String
Dim calc_result As Variant
Var.AgentSalesMeta = ReadAgentSalesWorkbook.Run(Var.agentSalesFilePath)
Var.ProductSalesMeta = ReadProductSalesWorkbook.Run(Var.productSalesPath)
Var.AgentWorkingPerformanceMeta = ReadAgentWorkingPerfWorkbook.Run(Var.agentWorkingPerformancePath)
Var.CombinedSalesMeta = Array(Var.AgentSalesMeta, Var.ProductSalesMeta, Var.AgentWorkingPerformanceMeta)
Dim file_path As String
file_path = Var.output_report_directory & "\output_report.xlsx"
' empty workbook
' EmptyWorkbook (file_path)
' delete file if exist
Common.DeleteFileIfExist (file_path)
Common.createNewXlsx (file_path)
Dim wb As Workbook
Set wb = Workbooks.Open(file_path)
If frmMain.chkSalesAnalysisRpt.Value = True Then
' SAMonthAndQuart
calc_result = CalcSalesAnalysisMonthlyAndQuart(Var.CombinedSalesMeta)
WriteSalesAnalysisMonthlyAndQuart calc_result, file_path, wb
End If
If frmMain.chkProductAnalysisRpt.Value = True Then
' write sales analysis product category
' SAProductCategory
calc_result = CalcSalesAnalysisFileSalesAmount(Var.CombinedSalesMeta)
WriteSalesAnalysisFileSalesAmount calc_result, file_path, wb
End If
If frmMain.chkProductAnalysisRpt.Value = True Then
calc_result = CalcSalesAnalysisFileSalesUnit(Var.CombinedSalesMeta)
WriteSalesAnalysisFileSalesUnit calc_result, file_path, wb
End If
If frmMain.chkAgentPerformanceAnalysisRpt.Value = True Then
calc_result = APAnalysis_Calc(Var.CombinedSalesMeta)
APAnalysis_WriteTable calc_result, file_path, wb
End If
If frmMain.chkNoOfCasesRpt.Value = True Then
calc_result = NoOfCasesTable_Calc(Var.CombinedSalesMeta)
NoOfCasesTable_WriteTable calc_result, file_path, wb
End If
wb.Save
wb.Close
MsgBox "generate report done"
Debug.Print "done"
End Sub
Sub GenChartReport()
Dim sPath As String
Dim calc_result As Variant
Dim file_path As String
' NOTE: for debug work
sPath = "C:\temp\xlsx\Agent_Sales.xlsx"
Var.AgentSalesMeta = ReadAgentSalesWorkbook.Run(sPath)
' NOTE: for debug work
sPath = "C:\temp\xlsx\Product_Sales.xlsx"
Var.ProductSalesMeta = ReadProductSalesWorkbook.Run(sPath)
' NOTE: for debug work
sPath = "C:\temp\xlsx\Agent_Working_Performance.xlsx"
Var.AgentWorkingPerformanceMeta = ReadAgentWorkingPerfWorkbook.Run(sPath)
Var.CombinedSalesMeta = Array(Var.AgentSalesMeta, Var.ProductSalesMeta, Var.AgentWorkingPerformanceMeta)
' Const file_path As String = "D:\_workspace\carousell-comission-playlist\jimmycheung93\task4\_poc\main_xlsm\helloworld_graph.xlsm"
' creasteXlsm(FILE_PATH)
file_path = Var.output_report_directory & "\output_report_chart.xlsx"
' vba delete file if exist
DeleteFileIfExist (file_path)
createNewXlsx (file_path)
'EmptyWorkbook (file_path)
Dim wb As Workbook
Set wb = Workbooks.Open(file_path)
If frmMain.chkSalesAnalysisMonthAndQuartery.Value = True Then
' Sales Analysis (Monthly & Quartery)
AddSheet file_path, "Sales Analysis Monthly_Quartery"
calc_result = CalcSalesAnalysisMonthlyAndQuart(CombinedSalesMeta)
SAMonthAndQuartGraph.MonthlySalesAmountTable calc_result, file_path
SAMonthAndQuartGraph.MonthlySalesAmountGraph file_path
SAMonthAndQuartGraph.MonthlySalesComissionTable calc_result, file_path
SAMonthAndQuartGraph.MonthlySalesComissionGraph file_path
End If
If frmMain.chkSalesAnalysisProductCategory.Value = True Then
' Sales Analysis (Product Category)
AddSheet file_path, "Sales Analysis Product Category"
calc_result = CalcSalesAnalysisFileSalesAmount(CombinedSalesMeta)
SAProdCatGraph.SalesAmountTable calc_result, file_path, 1
SAProdCatGraph.SalesAmountGraph calc_result, file_path, 1
calc_result = CalcSalesAnalysisFileSalesUnit(CombinedSalesMeta)
SAProdCatGraph.SalesUnitTable calc_result, file_path, 1
SAProdCatGraph.SalesUnitGraph calc_result, file_path, 1
End If
If frmMain.chkAgentPerformanceAnalysis.Value = True Then
' Agent performance analysis(Comm
AddSheet file_path, "Agent performance analysis"
calc_result = APAnalysis_Calc(CombinedSalesMeta)
APAnalysisGraph.TeamATotalSalesCommisionPerformanceTable calc_result, file_path
APAnalysisGraph.TeamATotalSalesCommisionPerformanceGraph calc_result, file_path
APAnalysisGraph.TeamBTotalSalesCommisionPerformanceTable calc_result, file_path
APAnalysisGraph.TeamBTotalSalesCommisionPerformanceGraph calc_result, file_path
' Rank of agent's sales commission (monthly)
APAnalysisGraph.RankOfAgentSalesCommMonthlyTable calc_result, file_path
APAnalysisGraph.RankOfAgentSalesCommMonthlyGraph calc_result, file_path
End If
If frmMain.chkCasePersistency.Value = True Then
' Case persistency
AddSheet file_path, "Case persistency"
calc_result = NoOfCasesTable_Calc(CombinedSalesMeta)
CasePersistencyGraph.TeamACaseDistributionTable calc_result, file_path
CasePersistencyGraph.TeamACaseDistributionGraph calc_result, file_path
CasePersistencyGraph.TeamBCaseDistributionTable calc_result, file_path
CasePersistencyGraph.TeamBCaseDistributionGraph calc_result, file_path
End If
wb.Save
wb.Close
MsgBox "generate report done"
Debug.Print "done"
End Sub
Function DeleteFileIfExist(file_path As String)
On Error GoTo eh
If Dir(file_path) <> "" Then
Kill file_path
End If
Done:
Exit Function
eh:
Debug.Print "DeleteFileIfExist:Error: " & Err.Description
End Function
Function createNewXlsx(file_path As String)
Dim wb As Workbook
Set wb = Workbooks.Add
wb.SaveAs file_path
wb.Close
End Function
Function SortArray(ByRef arr() As Double) As Double()
Dim i As Long, j As Long
Dim temp As Variant
For i = LBound(arr) To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If arr(i) < arr(j) Then
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
End If
Next j
Next i
SortArray = arr
End Function
Function AddSheet(ByVal file_path As String, ByVal sheet_name As String)
Dim wb As Workbook
Dim ws As Worksheet
' Open the workbook
Set wb = Workbooks.Open(file_path)
' Check if the sheet exists
On Error Resume Next
Set ws = wb.Sheets(sheet_name)
On Error GoTo 0
' If not found, create a new sheet
If ws Is Nothing Then
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = sheet_name
Else
' Empty the entire sheet
ws.UsedRange.ClearContents
End If
End Function
Function GetQuarterFromMonth(ByVal month As Integer) As Integer
GetQuarterFromMonth = Int((month - 1) / 3) + 1
End Function
Function ConvLetterMonthToIntMonth(str_letter_month As String)
Select Case str_letter_month
Case "Jan"
ConvLetterMonthToIntMonth = "1"
Case "Feb"
ConvLetterMonthToIntMonth = "2"
Case "Mar"
ConvLetterMonthToIntMonth = "3"
Case "Apr"
ConvLetterMonthToIntMonth = "4"
Case "May"
ConvLetterMonthToIntMonth = "5"
Case "Jun"
ConvLetterMonthToIntMonth = "6"
Case "Jul"
ConvLetterMonthToIntMonth = "7"
Case "Aug"
ConvLetterMonthToIntMonth = "8"
Case "Sep"
ConvLetterMonthToIntMonth = "9"
Case "Oct"
ConvLetterMonthToIntMonth = "10"
Case "Nov"
ConvLetterMonthToIntMonth = "11"
Case "Dec"
ConvLetterMonthToIntMonth = "12"
End Select
End Function
Sub ShowLogin()
frmLogin.Show
End Sub
' get the value from cell for a given address
Function readCell(sheet_name as string, cell_addr As String)
readCell = Worksheets(sheet_name).Range(cell_addr).Value
End Function
Sub initAccountFromAccountSheet()
Dim i As Integer
Dim account_ws As Worksheet
Set account_ws = Worksheets("account")
i = 0
For i = 1 To 99
Var.usernames(i) = readCell("account", "A" & CStr(i + 1))
Var.passwords(i) = readCell("account", "B" & CStr(i + 1))
Var.teams(i) = readCell("account", "C" & CStr(i + 1))
Var.ages(i) = readCell("account", "D" & CStr(i + 1))
Next i
End Sub

47
task4/1/Config.bas Normal file
View File

@@ -0,0 +1,47 @@
Attribute VB_Name = "Config"
Option Explicit
Sub init()
STRING_SEPERATOR = "#_STRING_SEPERATOR_#"
SALES_ANALYSIS_COL_MONTH = "A"
SALES_ANALYSIS_COL_QUARTER = "B"
SALES_ANALYSIS_COL_PRODUCT_CATEGORY = "C"
SALES_ANALYSIS_COL_SELLING_UNIT = "D"
SALES_ANALYSIS_COL_MONTHLY_SALES = "E"
SALES_ANALYSIS_COL_QUARTELY_SALES = "F"
SALES_ANALYSIS_COL_COMMISSION = "G"
SALES_ANALYSIS_COL_MONTHLY_MARGIN = "H"
SALES_ANALYSIS_COL_QUATERLY_MARGIN = "I"
SALES_ANALYSIS_COL_QUATERLY_COMMISSION_ = "J"
'row
SALES_ANALYSIS_ROW_JANUARY = "2"
SALES_ANALYSIS_ROW_FEBURARY = "3"
SALES_ANALYSIS_ROW_MARCH = "4"
SALES_ANALYSIS_ROW_APRIL = "5"
SALES_ANALYSIS_ROW_MAY = "6"
SALES_ANALYSIS_ROW_JUNE = "7"
SALES_ANALYSIS_ROW_JULY = "8"
SALES_ANALYSIS_ROW_AUGEST = "9"
SALES_ANALYSIS_ROW_SEPTEMBER = "10"
SALES_ANALYSIS_ROW_OCTOBER = "11"
SALES_ANALYSIS_ROW_NOVEMBER = "12"
SALES_ANALYSIS_ROW_DECEMBER = "13"
NumOfSales = 20
SALES_ARRAY = Array("Alex", "Ben", "Candy", "Danny", "Eason", "Filex", "Gary", "Henry", "Irene", "Jenny")
Dim top_comission(12, 3) As Double
Set monthly_commission_per_agent = CreateObject("Scripting.Dictionary")
Set monthly_product_sales_selling_unit_per_agent = CreateObject("Scripting.Dictionary")
Set monthly_product_sales_selling_price_per_agent = CreateObject("Scripting.Dictionary")
Set monthly_product_sales_per_agent = CreateObject("Scripting.Dictionary")
MONTH_NAMES = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Var.output_report_directory = "C:\temp"
End Sub

296
task4/1/NoOfCasesTable.bas Normal file
View File

@@ -0,0 +1,296 @@
Attribute VB_Name = "NoOfCasesTable"
Function NoOfCasesTable_Calc(ByVal TablesMeta As Variant) As Variant
Debug.Print "helloworld"
Set new_case_per_agent = CreateObject("Scripting.Dictionary")
Set collapsed_case_per_agent = CreateObject("Scripting.Dictionary")
Set case_persistency_by_agent = CreateObject("Scripting.Dictionary")
Dim case_persistency_team_a As Double
Dim case_persistency_team_b As Double
'case_team_a_meta
Dim case_team_a_meta As Variant
Dim case_team_b_meta As Variant
Dim agent_sales_table As Variant
Dim product_sales_meta As Variant
Dim product_sales_table As Variant
Dim val_agent_name As String
Dim val_team As String
agent_sales_table = TablesMeta(0)
Dim agent_sales_table_rows As Variant
agent_sales_table_rows = agent_sales_table(0)
product_sales_table = TablesMeta(1)
Dim product_sales_table_row As Variant
product_sales_table_row = product_sales_table(0)
agent_working_performance_table = TablesMeta(2)
Dim agent_working_performance_table_rows As Variant
agent_working_performance_table_rows = agent_working_performance_table(0)
Dim val_product_sales_selling_unit As String
Dim sales_selling_unit_TA As Integer
Dim sales_selling_unit_TB As Integer
Dim team As String
For ps = 1 To agent_working_performance_table(1)
val_agent_name = agent_working_performance_table_rows(ps, 2)
val_team = agent_working_performance_table_rows(ps, 3)
num_new_case = agent_working_performance_table_rows(ps, 4)
num_collapsed_case = agent_working_performance_table_rows(ps, 5)
If (Not (IsEmpty(val_agent_name)) And Not (new_case_per_agent.exists(val_agent_name))) Then
new_case_per_agent(val_agent_name) = 0
End If
new_case_per_agent(val_agent_name) = new_case_per_agent(val_agent_name) + num_new_case
If (Not (IsEmpty(val_agent_name)) And Not (collapsed_case_per_agent.exists(val_agent_name))) Then
collapsed_case_per_agent(val_agent_name) = 0
End If
collapsed_case_per_agent(val_agent_name) = collapsed_case_per_agent(val_agent_name) + num_collapsed_case
If (val_team = "A") Then
new_case_team_a = new_case_team_a + num_new_case
collapsed_case_team_a = collapsed_case_team_a + num_collapsed_case
End If
If (val_team = "B") Then
new_case_team_b = new_case_team_b + num_new_case
collapsed_case_team_b = collapsed_case_team_b + num_collapsed_case
End If
Next ps
For s = 0 To UBound(SALES_ARRAY)
sales_name = SALES_ARRAY(s)
collapsed_case = collapsed_case_per_agent(sales_name)
new_case = new_case_per_agent(sales_name)
case_persistency_by_agent(sales_name) = (new_case - collapsed_case) / new_case
Next s
case_persistency_team_a = (new_case_team_a - collapsed_case_team_a) / new_case_team_a
case_persistency_team_b = (new_case_team_b - collapsed_case_team_b) / new_case_team_b
case_team_a_meta = Array(new_case_team_a, collapsed_case_team_a)
case_team_b_meta = Array(new_case_team_b, collapsed_case_team_b)
NoOfCasesTable_Calc = Array(1, sales_selling_unit_TA, sales_selling_unit_TB, case_persistency_team_a, case_persistency_team_b, case_team_a_meta, case_team_b_meta)
End Function
Function NoOfCasesTable_WriteTable(ByVal calc_result As Variant, ByVal file_path As String, ByRef wb As Workbook)
Dim sales_selling_unit_TA As Integer
Dim sales_selling_unit_TB As Integer
sales_selling_unit_TA = calc_result(1)
sales_selling_unit_TB = calc_result(2)
Dim case_persistency_team_a As Double
Dim case_persistency_team_b As Double
case_persistency_team_a = calc_result(3)
case_persistency_team_b = calc_result(4)
Const TOP_ROW As Long = 1
Dim ws As Worksheet
Dim startCell As Range
Dim tempArray() As Variant
Dim i As Long
' Check if the sheet exists
On Error Resume Next
Set ws = wb.Sheets("No. of cases")
On Error GoTo 0
' If not found, create a new sheet
If ws Is Nothing Then
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = "No. of cases"
Else
' Empty the entire sheet
ws.UsedRange.ClearContents
End If
' Write month names
Set startCell = ws.Range("A1")
tempArray = Array("Case Persistency")
For i = LBound(tempArray) To UBound(tempArray)
startCell.Offset(0, i).Value = tempArray(i)
Next i
' Write month names
Set startCell = ws.Range("A2")
tempArray = Array("Name", "No of new case", "No. of collpased case", "Case Persistency")
For i = LBound(tempArray) To UBound(tempArray)
startCell.Offset(0, i).Value = tempArray(i)
Next i
' Write month names
Set startCell = ws.Range("A3")
For i = LBound(SALES_ARRAY) To UBound(SALES_ARRAY)
startCell.Offset(i, 0).Value = SALES_ARRAY(i)
Next i
' Write month names
Set startCell = ws.Range("B3")
' For sales_name = LBound(SALES_ARRAY) To UBound(SALES_ARRAY)
For s = 0 To UBound(SALES_ARRAY)
sales_name = SALES_ARRAY(s)
startCell.Offset(s, 0).Value = new_case_per_agent(sales_name)
Next s
' Write month names
Set startCell = ws.Range("C3")
' For sales_name = LBound(SALES_ARRAY) To UBound(SALES_ARRAY)
For s = 0 To UBound(SALES_ARRAY)
sales_name = SALES_ARRAY(s)
startCell.Offset(s, 0).Value = collapsed_case_per_agent(sales_name)
Next s
' Write month names
Set startCell = ws.Range("D3")
' For sales_name = LBound(SALES_ARRAY) To UBound(SALES_ARRAY)
For s = 0 To UBound(SALES_ARRAY)
sales_name = SALES_ARRAY(s)
startCell.Offset(s, 0).Value = case_persistency_by_agent(sales_name)
startCell.Offset(s, 0).NumberFormat = "0.00%"
Next s
' Write month names
Set startCell = ws.Range("A14")
tempArray = Array("Team A total", "Team B Total")
For i = LBound(tempArray) To UBound(tempArray)
startCell.Offset(i, 0).Value = tempArray(i)
Next i
' Write month names
Set startCell = ws.Range("B14")
tempArray = Array("Team A total", "Team B Total")
startCell.Offset(0, 0).Value = new_case_team_a
startCell.Offset(1, 0).Value = new_case_team_b
' Write month names
Set startCell = ws.Range("C14")
tempArray = Array("Team A total", "Team B Total")
startCell.Offset(0, 0).Value = collapsed_case_team_a
startCell.Offset(1, 0).Value = collapsed_case_team_b
' Write month names
Set startCell = ws.Range("D14")
tempArray = Array("Team A total", "Team B Total")
startCell.Offset(0, 0).Value = case_persistency_team_a
startCell.Offset(1, 0).Value = case_persistency_team_b
startCell.Offset(0, 0).NumberFormat = "0.00%"
startCell.Offset(1, 0).NumberFormat = "0.00%"
' styling
Dim ranges_need_paint As Variant
For i = 0 To 100
ws.Range("A1").Offset(0, i).EntireColumn.AutoFit
Next i
For i = 0 To 3
Range("A1").Offset(0, i).EntireColumn.ColumnWidth = 20
Next i
ranges_need_paint = Array("A1")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(68, 114, 196)
.Font.Color = RGB(255, 255, 255)
End With
Next r
ranges_need_paint = Array("A2")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Font.Color = RGB(48, 84, 150)
End With
Next r
ranges_need_paint = Array("B2:C2")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Font.Color = RGB(48, 84, 150)
.Font.Bold = True
End With
Next r
ranges_need_paint = Array("D2")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Font.Color = RGB(0, 0, 0)
.Font.Bold = True
End With
Next r
ranges_need_paint = Array("A3:D3", "A5:D5", "A7:D7", "A9:D9", "A11:D11", "A13:D13", "A15:D15")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(217, 225, 242)
End With
Next r
With Range("B2:D15")
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
End With
For Each r In Array("A2:D2", "A3:D15")
With Range(r).Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Range(r).Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Range(r).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Range(r).Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
Next r
End Function

47
task4/1/Notes.bas Normal file
View File

@@ -0,0 +1,47 @@
Attribute VB_Name = "Notes"
' naming convention
' main.xlsx
' main_xlsx
' - columns
' - Name
' - Team
' - Age
' main_xlsx_helloworld
' Agent_Sales.xlsx
' as_xlsx
' - columns
' - Sales No.
' - Date
' - Agent Name
' - Team
' - Selling Price Commision(%)
' - as_xlsx_helloworld_pivot
' - as_xlsx_get_month_best_agent
' - as_xlsx_get_agent_monthly_sale
' Agent_Working_Performance.xlsx
' awp_xlsx
' - columns
' - Date
' - Name
' - Team
' - No. of New Case
' - No. of Collapsed Case
' - awp_xlsx_helloworld_pivot
' - awp_xlsx_new_case_pivot
' - awp_xlsx_collapsed_case_pivot
' - awp_xlsx_case_persistency_pivot
' Product_Sales.xlsx
' ps_xlsx
' - columns
' - Sales No.
' - Date
' - Product Category
' - Selling Unit
' - Selling Price

View File

@@ -0,0 +1,79 @@
Attribute VB_Name = "ReadAgentSalesWorkbook"
Function Run(ByRef sPath As String) As Variant
Dim wb As Workbook
Dim arrResults(999, 20) As Variant
Dim row() As Variant
Dim i As Integer
Dim row_count As Integer
Dim firstRow As Boolean
Dim rw As Range
' Try to open the workbook
On Error Resume Next
Set wb = Workbooks.Open(sPath)
On Error GoTo 0
' Check if the opening was successful
If wb Is Nothing Then
MsgBox "Could not open workbook at " & sPath, vbCritical, "Error"
Exit Function
End If
row_count = 0
If Not wb.Sheets("Sheet1") Is Nothing Then
' Read data from Sheet1
For Each rw In wb.Sheets("Sheet1").UsedRange.Rows
' Check if first cell is empty
If Trim(rw.Cells(1)) <> "" Then
' Print value of first column of current row to immediate window
row_count = row_count + 1
Else
' First cell in current row is empty, so break the loop
Exit For
End If
Next rw
End If
' read table content
i = 1
firstRow = True
' Look for Sheet1 and stop execution if it doesn't exist
If Not wb.Sheets("Sheet1") Is Nothing Then
' Read data from Sheet1
For Each rw In wb.Sheets("Sheet1").UsedRange.Rows
' Check if first cell is empty
If (firstRow = False) Then
If (Trim(rw.Cells(1)) <> "") Then
' Print value of first column of current row to immediate window
arrResults(i, 1) = rw.Cells(1).Value
arrResults(i, 2) = rw.Cells(2).Value
arrResults(i, 3) = rw.Cells(3).Value
arrResults(i, 4) = rw.Cells(4).Value
arrResults(i, 5) = rw.Cells(5).Value
arrResults(i, 6) = rw.Cells(6).Value
i = i + 1
Else
' First cell in current row is empty, so break the loop
Exit For
End If
End If
firstRow = False
Next rw
Else
MsgBox """Sheet1"" does not exist in workbook at " & sPath, vbExclamation, "Warning"
Exit Function
End If
wb.Close savechanges:=False
Run = Array(arrResults, row_count - 1)
End Function

View File

@@ -0,0 +1,82 @@
Attribute VB_Name = "ReadAgentWorkingPerfWorkbook"
Function Run(ByRef sPath As String) As Variant
Dim wb As Workbook
Dim arrResults(999, 20) As Variant
Dim row() As Variant
Dim i As Integer
Dim row_count As Integer
Dim firstRow As Boolean
Dim rw As Range
' Try to open the workbook
On Error Resume Next
Set wb = Workbooks.Open(sPath)
On Error GoTo 0
' Check if the opening was successful
If wb Is Nothing Then
MsgBox "Could not open workbook at " & sPath, vbCritical, "Error"
Exit Function
End If
row_count = 0
If Not wb.Sheets("Sheet1") Is Nothing Then
' Read data from Sheet1
For Each rw In wb.Sheets("Sheet1").UsedRange.Rows
' Check if first cell is empty
If Trim(rw.Cells(1)) <> "" Then
' Print value of first column of current row to immediate window
row_count = row_count + 1
Else
' First cell in current row is empty, so break the loop
Exit For
End If
Next rw
End If
' read table content
i = 1
firstRow = True
' Look for Sheet1 and stop execution if it doesn't exist
If Not wb.Sheets("Sheet1") Is Nothing Then
' Read data from Sheet1
For Each rw In wb.Sheets("Sheet1").UsedRange.Rows
' Check if first cell is empty
If (firstRow = False) Then
If (Trim(rw.Cells(1)) <> "") Then
' Print value of first column of current row to immediate window
arrResults(i, 1) = rw.Cells(1).Value
arrResults(i, 2) = rw.Cells(2).Value
arrResults(i, 3) = rw.Cells(3).Value
arrResults(i, 4) = rw.Cells(4).Value
arrResults(i, 5) = rw.Cells(5).Value
arrResults(i, 6) = rw.Cells(6).Value
i = i + 1
Else
' First cell in current row is empty, so break the loop
Exit For
End If
End If
firstRow = False
Next rw
Else
MsgBox """Sheet1"" does not exist in workbook at " & sPath, vbExclamation, "Warning"
Exit Function
End If
Debug.Print arrResults(150, 2)
wb.Close savechanges:=False
Run = Array(arrResults, row_count - 1)
End Function

View File

@@ -0,0 +1,79 @@
Attribute VB_Name = "ReadProductSalesWorkbook"
Function Run(ByRef sPath As String) As Variant
Dim wb As Workbook
Dim arrResults(999, 20) As Variant
Dim row() As Variant
Dim i As Integer
Dim row_count As Integer
Dim firstRow As Boolean
Dim rw As Range
' Try to open the workbook
On Error Resume Next
Set wb = Workbooks.Open(sPath)
On Error GoTo 0
' Check if the opening was successful
If wb Is Nothing Then
MsgBox "Could not open workbook at " & sPath, vbCritical, "Error"
Exit Function
End If
row_count = 0
If Not wb.Sheets("Sheet1") Is Nothing Then
' Read data from Sheet1
For Each rw In wb.Sheets("Sheet1").UsedRange.Rows
' Check if first cell is empty
If Trim(rw.Cells(1)) <> "" Then
' Print value of first column of current row to immediate window
row_count = row_count + 1
Else
' First cell in current row is empty, so break the loop
Exit For
End If
Next rw
End If
' read table content
i = 1
firstRow = True
' Look for Sheet1 and stop execution if it doesn't exist
If Not wb.Sheets("Sheet1") Is Nothing Then
' Read data from Sheet1
For Each rw In wb.Sheets("Sheet1").UsedRange.Rows
' Check if first cell is empty
If (firstRow = False) Then
If (Trim(rw.Cells(1)) <> "") Then
' Print value of first column of current row to immediate window
arrResults(i, 1) = rw.Cells(1).Value
arrResults(i, 2) = rw.Cells(2).Value
arrResults(i, 3) = rw.Cells(3).Value
arrResults(i, 4) = rw.Cells(4).Value
arrResults(i, 5) = rw.Cells(5).Value
arrResults(i, 6) = rw.Cells(6).Value
i = i + 1
Else
' First cell in current row is empty, so break the loop
Exit For
End If
End If
firstRow = False
Next rw
Else
MsgBox """Sheet1"" does not exist in workbook at " & sPath, vbExclamation, "Warning"
Exit Function
End If
Debug.Print arrResults(150, 1)
wb.Close savechanges:=False
Run = Array(arrResults, row_count - 1)
End Function

313
task4/1/SAMonthAndQuart.bas Normal file
View File

@@ -0,0 +1,313 @@
Attribute VB_Name = "SAMonthAndQuart"
Function CalcSalesAnalysisMonthlyAndQuart(ByVal TablesMeta As Variant) As Variant
Dim quarter(4) As Double
Dim quaterly_margin(4) As Double
Dim quaterly_comission(4) As Double
Dim quaterly_sales(4) As Double
Dim calc_monthly_product_category(12) As String
Dim monthly_product_category(12) As String
Dim monthly_selling_unit(12) As Double
Dim monthly_sales(12) As Double
Dim monthly_margin(12) As Double
Dim monthly_commission(12) As Double
' Dim monthly_commission_per_agent(999, 2) As String
Dim comission_array_for_sorting(999) As Double
Dim monthly_commission_per_agent
Set monthly_commission_per_agent = CreateObject("Scripting.Dictionary")
Dim sales_agent_names
Set sales_agent_names = CreateObject("Scripting.Dictionary")
Dim val_agent_sale_sales_num As String
Dim val_agent_sale_date As String
Dim val_agent_sale_agent_name As String
Dim val_agent_sale_team As String
Dim val_agent_sale_selling_price As String
Dim val_agent_sale_commision_pct As String
Dim val_product_sales_sales_num As String
Dim val_product_sales_date As String
Dim val_product_sales_product_category As String
Dim val_product_sales_selling_unit As String
Dim val_product_sales_selling_price As String
Dim val_product_sales_comission As String
Dim val_product_sales_total_comission As String
' product sales calculation
Dim val_product_sales_margin As Double
Dim dt As Date
Dim intMonth As Integer
Dim intQuarter As Integer
Dim agent_sales_table As Variant
Dim product_sales_table As Variant
Dim agent_working_performance As Variant
agent_sales_table = TablesMeta(0)
product_sales_table = TablesMeta(1)
agent_working_performance = TablesMeta(2)
Dim agent_sales_table_row As Variant
agent_sales_table_rows = agent_sales_table(0)
Dim product_sales_table_row As Variant
product_sales_table_row = product_sales_table(0)
Dim agent_working_performance_row As Variant
agent_working_performance_row = agent_working_performance(0)
Dim top_comission(12, 3) As Double
For i = 1 To agent_sales_table(1)
val_agent_sale_date = agent_sales_table_rows(i, 2)
dt = DateValue(val_agent_sale_date)
intMonth = month(dt)
intQuarter = Int((intMonth - 1) / 3) + 1
val_agent_sale_sales_num = agent_sales_table_rows(i, 1)
val_agent_sale_agent_name = agent_sales_table_rows(i, 3)
val_agent_sale_team = agent_sales_table_rows(i, 4)
val_agent_sale_selling_price = agent_sales_table_rows(i, 5)
val_agent_sale_commision_pct = agent_sales_table_rows(i, 6)
Next i
For ps = 1 To product_sales_table(1)
val_product_sales_date = product_sales_table_row(ps, 2)
dt = DateValue(val_product_sales_date)
intMonth = month(dt)
intQuarter = Int((intMonth - 1) / 3) + 1
val_agent_sale_agent_name = agent_sales_table_rows(ps, 3)
val_product_sales_sales_num = product_sales_table_row(ps, 1)
val_product_sales_product_category = product_sales_table_row(ps, 3)
val_product_sales_selling_unit = product_sales_table_row(ps, 4)
val_product_sales_selling_price = product_sales_table_row(ps, 5)
val_agent_sale_commision_pct = agent_sales_table_rows(ps, 6)
' val_product_sales_total_comission = product_sales_table_row(i, 7)
If InStr(calc_monthly_product_category(intMonth), val_product_sales_product_category) < 1 Then
calc_monthly_product_category(intMonth) = calc_monthly_product_category(intMonth) + STRING_SEPERATOR + val_product_sales_product_category
End If
'calculate comission
val_product_sales_comission = val_product_sales_selling_unit * val_product_sales_selling_price * val_agent_sale_commision_pct
product_sales_table_row(ps, 6) = val_product_sales_comission
' calc margin
val_product_sales_margin = val_product_sales_selling_price - val_product_sales_comission
product_sales_table_row(ps, 7) = val_product_sales_margin
'monthly calculation
monthly_selling_unit(intMonth) = monthly_selling_unit(intMonth) + val_product_sales_selling_unit
monthly_sales(intMonth) = monthly_sales(intMonth) + val_product_sales_selling_price
monthly_commission(intMonth) = monthly_commission(intMonth) + val_product_sales_comission
monthly_margin(intMonth) = monthly_margin(intMonth) + val_product_sales_margin
'quartely calculation
quaterly_sales(intQuarter) = quaterly_sales(intQuarter) + val_product_sales_comission
quaterly_margin(intQuarter) = quaterly_margin(intQuarter) + val_product_sales_margin
quaterly_comission(intQuarter) = quaterly_comission(intQuarter) + val_product_sales_comission
Next ps
' get monthly sales by agent
For ps = 1 To product_sales_table(1)
Dim temp_key As String
temp_key = val_agent_sale_agent_name + "," + CStr(intMonth)
If (Not (IsEmpty(temp_key)) And Not (monthly_commission_per_agent.exists(temp_key))) Then
For j = 1 To 12
monthly_commission_per_agent(val_agent_sale_agent_name + "," + CStr(j)) = 0
Next j
End If
monthly_commission_per_agent(temp_key) = monthly_commission_per_agent(temp_key) + val_product_sales_comission
Next ps
' get first 3 per comission per month
For m = 1 To 12
Dim temp_sort(20) As Double
j = 0
For Each agent_name_and_month In monthly_commission_per_agent.Keys
If (Split(agent_name_and_month, ",")(1) = CStr(m)) Then
temp_sort(j) = monthly_commission_per_agent(agent_name_and_month)
j = j + 1
End If
Next agent_name_and_month
sortedArray = SortArray(temp_sort)
top_comission(m, 0) = sortedArray(0)
top_comission(m, 1) = sortedArray(1)
top_comission(m, 2) = sortedArray(2)
' total comission
product_sales_table_row(m, 7) = product_sales_table_row(m, 6) + bonus
Next m
For m = 1 To 12
Dim temp() As String
temp = Split(calc_monthly_product_category(m), STRING_SEPERATOR)
monthly_product_category(m) = CStr(UBound(temp)) + "(" + Join(temp, ",") + ")"
Next m
'get the total commission with bonus
CalcSalesAnalysisMonthlyAndQuart = Array(monthly_product_category, monthly_selling_unit, monthly_sales, quaterly_sales, monthly_commission, monthly_margin, quaterly_margin, quaterly_comission)
End Function
Function WriteSalesAnalysisMonthlyAndQuart(ByVal calc_result As Variant, ByVal file_path As String, ByRef wb As Workbook)
Application.DisplayAlerts = False
Const HEADER_ROW As Long = 1
Const START_CELL As String = "A2"
Dim ws As Worksheet
Dim startCell As Range
' Open the workbook
' Set wb = Workbooks.Open(FILE_PATH)
' Check if the sheet exists
On Error Resume Next
Set ws = wb.Sheets("Sales Analysis Monthly & Quart")
On Error GoTo 0
' If not found, create a new sheet
If ws Is Nothing Then
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = "Sales Analysis Monthly & Quart"
Else
' Empty the entire sheet
ws.UsedRange.ClearContents
End If
' Write headers
With ws.Rows(HEADER_ROW)
.Cells(1).Value = "Month"
.Cells(2).Value = "Quarter"
.Cells(3).Value = "Product Category"
.Cells(4).Value = "Selling Unit"
.Cells(5).Value = "Monthly Sales"
.Cells(6).Value = "Quartely Sales"
.Cells(7).Value = "Commission"
.Cells(8).Value = "Monthly Margin"
.Cells(9).Value = "Quaterly Margin"
.Cells(10).Value = "Quaterly Commission"
End With
' Write month names
Set startCell = ws.Range("A2")
Dim monthNames() As Variant
monthNames = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
Dim monthly_product_category As Variant
Dim monthly_sales As Variant
monthly_product_category = calc_result(0)
monthly_selling_unit = calc_result(1)
monthly_sales = calc_result(2)
quaterly_sales = calc_result(3)
monthly_commission = calc_result(4)
monthly_margin = calc_result(5)
quaterly_margin = calc_result(6)
quaterly_comission = calc_result(7)
'output content
For m = LBound(monthNames) To UBound(monthNames)
Dim quarter, month As Integer
month = m + 1
quarter = GetQuarterFromMonth(month)
startCell.Offset(m, 0).Value = monthNames(m)
startCell.Offset(m, 1).Value = monthly_product_category(month)
startCell.Offset(m, 2).Value = monthly_selling_unit(month)
startCell.Offset(m, 3).Value = monthly_sales(month)
startCell.Offset(m, 4).Value = monthly_sales(month)
startCell.Offset(m, 5).Value = quaterly_sales(quarter)
startCell.Offset(m, 6).Value = monthly_commission(month)
startCell.Offset(m, 7).Value = monthly_margin(month)
startCell.Offset(m, 8).Value = quaterly_margin(quarter)
startCell.Offset(m, 9).Value = quaterly_comission(quarter)
Next m
Range("A1:J1").Interior.Color = RGB(252, 229, 205)
Dim column_used As Variant
column_used = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J")
For c = LBound(column_used) To UBound(column_used)
Columns(column_used(c)).EntireColumn.AutoFit
Next c
'rgb(255, 242, 204)
Range("A5:J7").Interior.Color = RGB(255, 242, 204)
Range("A11:J13").Interior.Color = RGB(255, 242, 204)
Dim columns_need_merge As Variant
columns_need_merge = Array("F", "I", "J")
For c = LBound(columns_need_merge) To UBound(columns_need_merge)
Dim column As String
column = columns_need_merge(c)
With Range(column & "2:" & column & "4")
.Merge ' merges cells F5, F6, and F7 into a single cell
.VerticalAlignment = xlVAlignCenter ' centering the text vertically within the merged cell
.HorizontalAlignment = xlHAlignRight ' centering the text horizontally across the merged cell
End With
With Range(column & "5:" & column & "7")
.Merge ' merges cells F5, F6, and F7 into a single cell
.VerticalAlignment = xlVAlignCenter ' centering the text vertically within the merged cell
.HorizontalAlignment = xlHAlignRight ' centering the text horizontally across the merged cell
End With
With Range(column & "8:" & column & "10")
.Merge ' merges cells F5, F6, and F7 into a single cell
.VerticalAlignment = xlVAlignCenter ' centering the text vertically within the merged cell
.HorizontalAlignment = xlHAlignRight ' centering the text horizontally across the merged cell
End With
With Range(column & "11:" & column & "13")
.Merge ' merges cells F5, F6, and F7 into a single cell
.VerticalAlignment = xlVAlignCenter ' centering the text vertically within the merged cell
.HorizontalAlignment = xlHAlignRight ' centering the text horizontally across the merged cell
End With
Next c
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function

View File

@@ -0,0 +1,169 @@
Attribute VB_Name = "SAMonthAndQuartGraph"
Function MonthlySalesAmountTable(ByVal calc_result As Variant, ByVal file_path As String)
Const HEADER_ROW As Long = 1
Const START_CELL As String = "A1"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Monthly_Quartery")
' Write headers
Set startCell = ws.Range(START_CELL)
With startCell
.Value = "Monthly Sales Amount in 2023"
End With
With startCell
.Offset(1, 0).Value = "date"
.Offset(1, 1).Value = "Monthly Sales"
End With
Set startCell = ws.Range("A3")
Dim monthNames() As Variant
monthNames = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Dim monthly_sales As Variant
monthly_sales = calc_result(2)
For m = LBound(monthNames) To UBound(monthNames)
startCell.Offset(m, 0).Value = monthNames(m)
startCell.Offset(m, 1).Value = monthly_sales(m + 1)
Next m
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function
Function MonthlySalesAmountGraph(ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Monthly_Quartery")
Range("A2:B14").Select
' insert graph
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("$A$2:$B$14")
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Date range"
Set cho = ws.ChartObjects(1)
Set cht = cho.Chart
' update chart styling
cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
'# set your axis in a variable
Set ax = cht.Axes(xlValue, xlPrimary)
'# Make sure your axis HAS a title
ax.HasTitle = True
With ax.AxisTitle.Format.TextFrame2.TextRange
.Characters.Text = "Primary Y-Axis"
With .Characters(1, 14).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
End With
cho.Top = 0
cho.Left = 0
cho.Width = 400
cho.Height = 300
End Function
Function MonthlySalesComissionTable(ByVal calc_result As Variant, ByVal file_path As String)
Const HEADER_ROW As Long = 1
Const START_CELL As String = "F1"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Monthly_Quartery")
' Write headers
Set startCell = ws.Range(START_CELL)
With startCell
.Value = "Monthly Sales Comission in 2023"
End With
With startCell
.Offset(1, 0).Value = "date"
.Offset(1, 1).Value = "Monthly Sales Commission"
End With
Set startCell = ws.Range("F3")
Dim monthNames() As Variant
monthNames = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
monthly_commission = calc_result(4)
For m = LBound(monthNames) To UBound(monthNames)
startCell.Offset(m, 0).Value = monthNames(m)
startCell.Offset(m, 1).Value = monthly_commission(m + 1)
Next m
' Save and close the workbook
' wb.Close SaveChanges:=True
End Function
Function MonthlySalesComissionGraph(ByVal file_path As String)
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Monthly_Quartery")
' insert graph
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("$F$2:$G$14")
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Date range chart2"
Set cho = ws.ChartObjects(2)
Set cht = cho.Chart
' update chart styling
cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
'# set your axis in a variable
Set ax = cht.Axes(xlValue, xlPrimary)
'# Make sure your axis HAS a title
ax.HasTitle = True
With ax.AxisTitle.Format.TextFrame2.TextRange
.Characters.Text = "Primary Y-Axis"
With .Characters(1, 14).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
End With
cho.Top = 0
cho.Left = 400
cho.Width = 400
cho.Height = 300
End Function
Function Helloworld()
Debug.Print "helloworld SalesAnalysisMonthAndQuartGraph"
End Function

227
task4/1/SAProdCatGraph.bas Normal file
View File

@@ -0,0 +1,227 @@
Attribute VB_Name = "SAProdCatGraph"
Function SalesAmountTable(ByVal calc_result As Variant, ByVal file_path As String, ByVal int_month As Integer)
Const START_CELL As String = "A1"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim row As Integer
' Load sales amount by month for different types of insurance
Dim TravelInsuranceByMonth() As Variant
Dim HealthInsuranceByMonth() As Variant
Dim LifeInsuranceByMonth() As Variant
Dim VehicleInsuranceByMonth() As Variant
Dim AccidentInsuranceByMonth() As Variant
TravelInsuranceByMonth = calc_result(0)
HealthInsuranceByMonth = calc_result(1)
LifeInsuranceByMonth = calc_result(2)
VehicleInsuranceByMonth = calc_result(3)
AccidentInsuranceByMonth = calc_result(4)
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Product Category")
Dim InstType() As Variant
InstType = Array("Accident insurance", "Vehicle insurance", "Life insurance", "Health insurance", "Travel insurance")
' Write headers
Set startCell = ws.Range(START_CELL)
'generate graph by month
For m = LBound(MONTH_NAMES) To UBound(MONTH_NAMES)
month_name = MONTH_NAMES(m)
row = 0
startCell.Offset(row, 0 + (m * 3)).Value = "Sales unit of " & month_name
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Type"
startCell.Offset(row, 1 + (m * 3)).Value = "Sales"
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Accident insurance"
startCell.Offset(row, 1 + (m * 3)).Value = AccidentInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Vehicle insurance"
startCell.Offset(row, 1 + (m * 3)).Value = VehicleInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Life insurance"
startCell.Offset(row, 1 + (m * 3)).Value = LifeInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Health insurance"
startCell.Offset(row, 1 + (m * 3)).Value = HealthInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Travel insurance"
startCell.Offset(row, 1 + (m * 3)).Value = TravelInsuranceByMonth(m + 1)
Next m
End Function
Function SalesAmountGraph(ByVal calc_result As Variant, ByVal file_path As String, ByVal int_month As Integer)
Dim wb As Workbook
Dim ws As Worksheet
' Define the top and left positions for each graph
Dim YEAR_GRAPHS_TOP As Variant
Dim YEAR_GRAPHS_LEFT As Variant
YEAR_GRAPHS_TOP = Array(0, 0, 0, 300, 300, 300, 600, 600, 600, 900, 900, 900)
YEAR_GRAPHS_LEFT = Array(0, 400, 800, 0, 400, 800, 0, 400, 800, 0, 400, 800)
' Define the range for data of each graph
Dim DATA_RANGES As Variant
DATA_RANGES = Array("A2:B7", "D2:E7", "G2:H7", "J2:K7", "M2:N7", "P2:Q7", "S2:T7", "V2:W7", "Y2:Z7", "AB2:AC7", "AE2:AF7", "AH2:AI7")
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Product Category")
'generate graph by month
For m = LBound(MONTH_NAMES) To UBound(MONTH_NAMES)
month_name = MONTH_NAMES(m)
data_range = DATA_RANGES(m)
' insert graph
ActiveSheet.Shapes.AddChart2(251, xlPie).Select
ActiveChart.SetSourceData Source:=Range(data_range)
ActiveChart.SetElement (msoElementLegendNone)
ActiveChart.SetElement (msoElementDataLabelCallout)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Sales amount of " & month_name
Selection.Format.TextFrame2.TextRange.Characters.Text = "Sales amount of " & month_name
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
cho.Top = YEAR_GRAPHS_TOP(m)
cho.Left = YEAR_GRAPHS_LEFT(m)
cho.Width = 400
cho.Height = 300
Next m
End Function
Function SalesUnitTable(ByVal calc_result As Variant, ByVal file_path As String, ByVal int_month As Integer)
Const START_CELL As String = "A10"
Dim wb As Workbook
Dim ws As Worksheet
Dim startCell As Range
Dim row As Integer
Dim TravelInsuranceByMonth As Variant
Dim HealthInsuranceByMonth As Variant
Dim LifeInsuranceByMonth As Variant
Dim VehicleInsuranceByMonth As Variant
Dim AccidentInsuranceByMonth As Variant
TravelInsuranceByMonth = calc_result(0)
HealthInsuranceByMonth = calc_result(1)
LifeInsuranceByMonth = calc_result(2)
VehicleInsuranceByMonth = calc_result(3)
AccidentInsuranceByMonth = calc_result(4)
' Open the workbook
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Product Category")
Dim InstType() As Variant
InstType = Array("Accident insurance", "Vehicle insurance", "Life insurance", "Health insurance", "Travel insurance")
' Write headers
Set startCell = ws.Range(START_CELL)
'generate graph by month
For m = LBound(MONTH_NAMES) To UBound(MONTH_NAMES)
month_name = MONTH_NAMES(m)
row = 0
startCell.Offset(row, 0 + (m * 3)).Value = "Sales amount of " & month_name
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Type"
startCell.Offset(row, 1 + (m * 3)).Value = "Sales"
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Accident insurance"
startCell.Offset(row, 1 + (m * 3)).Value = AccidentInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Vehicle insurance"
startCell.Offset(row, 1 + (m * 3)).Value = VehicleInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Life insurance"
startCell.Offset(row, 1 + (m * 3)).Value = LifeInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Health insurance"
startCell.Offset(row, 1 + (m * 3)).Value = HealthInsuranceByMonth(m + 1)
row = row + 1
startCell.Offset(row, 0 + (m * 3)).Value = "Travel insurance"
startCell.Offset(row, 1 + (m * 3)).Value = TravelInsuranceByMonth(m + 1)
Next m
End Function
Function SalesUnitGraph(ByVal calc_result As Variant, ByVal file_path As String, ByVal int_month As Integer)
Dim wb As Workbook
Dim ws As Worksheet
Dim YEAR_GRAPHS_TOP As Variant
Dim YEAR_GRAPHS_LEFT As Variant
YEAR_GRAPHS_TOP = Array(1200, 1200, 1200, 1200 + 300, 1200 + 300, 1200 + 300, 1200 + 600, 1200 + 600, 1200 + 600, 1200 + 900, 1200 + 900, 1200 + 900)
YEAR_GRAPHS_LEFT = Array(0, 400, 800, 0, 400, 800, 0, 400, 800, 0, 400, 800)
Dim DATA_RANGES As Variant
DATA_RANGES = Array("A11:B16", "D11:E16", "G11:H16", "J11:K16", "M11:N16", "P11:Q16", "S11:T16", "V11:W16", "Y11:Z16", "AB11:AC16", "AE11:AF16", "AH11:AI16")
Set wb = Workbooks.Open(file_path)
Set ws = wb.Sheets("Sales Analysis Product Category")
'generate graph by month
For m = LBound(MONTH_NAMES) To UBound(MONTH_NAMES)
month_name = MONTH_NAMES(m)
data_range = DATA_RANGES(m)
' insert graph
ActiveSheet.Shapes.AddChart2(251, xlPie).Select
ActiveChart.SetSourceData Source:=Range(data_range)
ActiveChart.SetElement (msoElementLegendNone)
ActiveChart.SetElement (msoElementDataLabelCallout)
ActiveChart.ChartTitle.Text = "Sales unit of " & month_name
Selection.Format.TextFrame2.TextRange.Characters.Text = "Sales unit of " & month_name
Set cho = ws.ChartObjects(ws.ChartObjects.Count)
Set cht = cho.Chart
cho.Top = YEAR_GRAPHS_TOP(m)
cho.Left = YEAR_GRAPHS_LEFT(m)
cho.Width = 400
cho.Height = 300
Next m
End Function
Function Helloworld()
Debug.Print "helloworld Sales_Analysis_Product_Category"
End Function

View File

@@ -0,0 +1,382 @@
Attribute VB_Name = "SAProductCategory"
Function CalcSalesAnalysisFileSalesAmount(ByVal TablesMeta As Variant) As Variant
Dim agent_sales_table As Variant
Dim product_sales_meta As Variant
Dim product_sales_table As Variant
Dim ps_rows As Double
Dim agent_working_performance As Variant
' agent_sales_table = TablesMeta(0)
' agent_working_performance = TablesMeta(2)
Dim VehicleInsuranceByMonth(12) As Double
Dim TravelInsuranceByMonth(12) As Double
Dim LifeInsuranceByMonth(12) As Double
Dim HealthInsuranceByMonth(12) As Double
Dim AccidentInsuranceByMonth(12) As Double
Dim MonthlyTotal(12) As Double
Dim QuartelyTotal(4) As Double
product_sales_table = TablesMeta(1)
Dim product_sales_table_row As Variant
product_sales_table_row = product_sales_table(0)
Dim val_agent_sale_sales_num As String
Dim val_agent_sale_date As String
Dim val_agent_sale_agent_name As String
Dim val_agent_sale_team As String
Dim val_agent_sale_selling_price As String
Dim val_agent_sale_commision_pct As String
Dim val_product_sales_sales_num As String
Dim val_product_sales_date As String
Dim val_product_sales_product_category As String
Dim val_product_sales_selling_unit As String
Dim val_product_sales_selling_price As String
Dim val_product_sales_comission As String
Dim val_product_sales_total_comission As String
Dim subColumn() As Variant
subColumn = Array("Travel insurance", "Health insurance", "Life insurance", "Vehicle insurance", "Accident insurance", "Monthly Total", "Quaterly Total")
For ps = 1 To product_sales_table(1)
val_product_sales_date = product_sales_table_row(ps, 2)
val_product_sales_selling_price = product_sales_table_row(ps, 5)
dt = DateValue(val_product_sales_date)
intMonth = month(dt)
intQuarter = Int((intMonth - 1) / 3) + 1
val_product_sales_product_category = product_sales_table_row(ps, 3)
If val_product_sales_product_category = "Travel insurance" Then
TravelInsuranceByMonth(intMonth) = TravelInsuranceByMonth(intMonth) + val_product_sales_selling_price
End If
If val_product_sales_product_category = "Health insurance" Then
HealthInsuranceByMonth(intMonth) = HealthInsuranceByMonth(intMonth) + val_product_sales_selling_price
End If
If val_product_sales_product_category = "Life insurance" Then
LifeInsuranceByMonth(intMonth) = LifeInsuranceByMonth(intMonth) + val_product_sales_selling_price
End If
If val_product_sales_product_category = "Vehicle insurance" Then
VehicleInsuranceByMonth(intMonth) = VehicleInsuranceByMonth(intMonth) + val_product_sales_selling_price
End If
If val_product_sales_product_category = "Accident insurance" Then
AccidentInsuranceByMonth(intMonth) = AccidentInsuranceByMonth(intMonth) + val_product_sales_selling_price
End If
MonthlyTotal(intMonth) = MonthlyTotal(intMonth) + val_product_sales_selling_price
QuartelyTotal(intQuarter) = QuartelyTotal(intQuarter) + val_product_sales_selling_price
Next ps
CalcSalesAnalysisFileSalesAmount = Array(TravelInsuranceByMonth, HealthInsuranceByMonth, LifeInsuranceByMonth, VehicleInsuranceByMonth, AccidentInsuranceByMonth, MonthlyTotal, QuartelyTotal)
End Function
Function CalcSalesAnalysisFileSalesUnit(ByVal TablesMeta As Variant) As Variant
Dim agent_sales_table As Variant
Dim product_sales_meta As Variant
Dim product_sales_table As Variant
Dim ps_rows As Double
Dim agent_working_performance As Variant
' agent_sales_table = TablesMeta(0)
' agent_working_performance = TablesMeta(2)
Dim VehicleInsuranceByMonth(12) As Double
Dim TravelInsuranceByMonth(12) As Double
Dim LifeInsuranceByMonth(12) As Double
Dim HealthInsuranceByMonth(12) As Double
Dim AccidentInsuranceByMonth(12) As Double
Dim MonthlyTotal(12) As Double
Dim QuartelyTotal(4) As Double
product_sales_table = TablesMeta(1)
Dim product_sales_table_row As Variant
product_sales_table_row = product_sales_table(0)
Dim val_agent_sale_sales_num As String
Dim val_agent_sale_date As String
Dim val_agent_sale_agent_name As String
Dim val_agent_sale_team As String
Dim val_agent_sale_selling_price As String
Dim val_agent_sale_commision_pct As String
Dim val_product_sales_sales_num As String
Dim val_product_sales_date As String
Dim val_product_sales_product_category As String
Dim val_product_sales_selling_unit As String
Dim val_product_sales_comission As String
Dim val_product_sales_total_comission As String
Dim subColumn() As Variant
subColumn = Array("Travel insurance", "Health insurance", "Life insurance", "Vehicle insurance", "Accident insurance", "Monthly Total", "Quaterly Total")
For ps = 1 To product_sales_table(1)
val_product_sales_date = product_sales_table_row(ps, 2)
val_product_sales_selling_unit = product_sales_table_row(ps, 4)
dt = DateValue(val_product_sales_date)
intMonth = month(dt)
intQuarter = Int((intMonth - 1) / 3) + 1
val_product_sales_product_category = product_sales_table_row(ps, 3)
If val_product_sales_product_category = "Travel insurance" Then
TravelInsuranceByMonth(intMonth) = TravelInsuranceByMonth(intMonth) + val_product_sales_selling_unit
End If
If val_product_sales_product_category = "Health insurance" Then
HealthInsuranceByMonth(intMonth) = HealthInsuranceByMonth(intMonth) + val_product_sales_selling_unit
End If
If val_product_sales_product_category = "Life insurance" Then
LifeInsuranceByMonth(intMonth) = LifeInsuranceByMonth(intMonth) + val_product_sales_selling_unit
End If
If val_product_sales_product_category = "Vehicle insurance" Then
VehicleInsuranceByMonth(intMonth) = VehicleInsuranceByMonth(intMonth) + val_product_sales_selling_unit
End If
If val_product_sales_product_category = "Accident insurance" Then
AccidentInsuranceByMonth(intMonth) = AccidentInsuranceByMonth(intMonth) + val_product_sales_selling_unit
End If
MonthlyTotal(intMonth) = MonthlyTotal(intMonth) + val_product_sales_selling_unit
QuartelyTotal(intQuarter) = QuartelyTotal(intQuarter) + val_product_sales_selling_unit
Next ps
CalcSalesAnalysisFileSalesUnit = Array(TravelInsuranceByMonth, HealthInsuranceByMonth, LifeInsuranceByMonth, VehicleInsuranceByMonth, AccidentInsuranceByMonth, MonthlyTotal, QuartelyTotal)
End Function
Function WriteSalesAnalysisFileSalesAmount(ByVal calc_result As Variant, ByVal file_path As String, ByRef wb As Workbook)
Dim TravelInsuranceByMonth As Variant
Dim HealthInsuranceByMonth As Variant
Dim LifeInsuranceByMonth As Variant
Dim VehicleInsuranceByMonth As Variant
Dim AccidentInsuranceByMonth As Variant
Dim MonthlyTotal As Variant
Dim QuartelyTotal As Variant
TravelInsuranceByMonth = calc_result(0)
HealthInsuranceByMonth = calc_result(1)
LifeInsuranceByMonth = calc_result(2)
VehicleInsuranceByMonth = calc_result(3)
AccidentInsuranceByMonth = calc_result(4)
MonthlyTotal = calc_result(5)
QuartelyTotal = calc_result(6)
Const HEADER_ROW As Long = 1
Const START_CELL As String = "A2"
Dim ws As Worksheet
Dim startCell As Range
' Check if the sheet exists
On Error Resume Next
Set ws = wb.Sheets("Sales Analysis Product Category")
On Error GoTo 0
' If not found, create a new sheet
If ws Is Nothing Then
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = "Sales Analysis Product Category"
Else
' Empty the entire sheet
ws.UsedRange.ClearContents
End If
' Write headers
With ws.Rows(HEADER_ROW)
.Cells(1).Value = "Sales Amount"
.Cells(3).Value = "Month"
End With
' Write month names
Set startCell = ws.Range("C2")
Dim monthNames() As Variant
monthNames = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
Dim i As Long
For i = LBound(monthNames) To UBound(monthNames)
startCell.Offset(0, i).Value = monthNames(i)
Next i
' Write headers
With ws.Rows(3)
.Cells(1).Value = "Product Category"
End With
' Write sub-column names
Set startCell = ws.Range("B3")
Dim subColumn() As Variant
subColumn = Array("Travel insurance", "Health insurance", "Life insurance", "Vehicle insurance", "Accident insurance", "Monthly Total", "Quaterly Total")
For sc = LBound(subColumn) To UBound(subColumn)
startCell.Offset(sc, 0).Value = subColumn(sc)
Next sc
Set startCell = ws.Range("C3")
For m = LBound(monthNames) To UBound(monthNames)
Dim int_quarter, int_month As Integer
int_month = m + 1
int_quarter = GetQuarterFromMonth(int_month)
startCell.Offset(0, m).Value = TravelInsuranceByMonth(int_month)
startCell.Offset(1, m).Value = HealthInsuranceByMonth(int_month)
startCell.Offset(2, m).Value = LifeInsuranceByMonth(int_month)
startCell.Offset(3, m).Value = VehicleInsuranceByMonth(int_month)
startCell.Offset(4, m).Value = AccidentInsuranceByMonth(int_month)
startCell.Offset(5, m).Value = MonthlyTotal(int_month)
startCell.Offset(6, m).Value = QuartelyTotal(int_quarter)
Next m
' Save and close the workbook
'wb.Close SaveChanges:=True
End Function
Function WriteSalesAnalysisFileSalesUnit(ByVal calc_result As Variant, ByVal file_path As String, ByRef wb As Workbook)
Application.DisplayAlerts = False
' Variables to hold the result of the calculation
' The calculation results are stored in arrays
' Each array holds the sales unit for a specific product category by month
' e.g. TravelInsuranceByMonth(1) = Sales unit of travel insurance in January
Dim TravelInsuranceByMonth() As Variant ' Sales unit of travel insurance by month
Dim HealthInsuranceByMonth() As Variant ' Sales unit of health insurance by month
Dim LifeInsuranceByMonth() As Variant ' Sales unit of life insurance by month
Dim VehicleInsuranceByMonth() As Variant ' Sales unit of vehicle insurance by month
Dim AccidentInsuranceByMonth() As Variant ' Sales unit of accident insurance by month
Dim MonthlyTotal() As Variant ' Sales unit of each product category by month (total)
Dim QuartelyTotal() As Variant ' Sales unit of each product category by quarter (total)
TravelInsuranceByMonth = calc_result(0) ' Sales unit of travel insurance by month
HealthInsuranceByMonth = calc_result(1) ' Sales unit of health insurance by month
LifeInsuranceByMonth = calc_result(2) ' Sales unit of life insurance by month
VehicleInsuranceByMonth = calc_result(3) ' Sales unit of vehicle insurance by month
AccidentInsuranceByMonth = calc_result(4) ' Sales unit of accident insurance by month
MonthlyTotal = calc_result(5) ' Sales unit of each product category by month (total)
QuartelyTotal = calc_result(6) ' Sales unit of each product category by quarter (total)
Const TOP_ROW As Long = 10
Const START_CELL As String = "A2"
Dim ws As Worksheet
Dim startCell As Range
' Check if the sheet exists
On Error Resume Next
Set ws = wb.Sheets("Sales Analysis Product Category")
On Error GoTo 0
' If not found, create a new sheet
If ws Is Nothing Then
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = "Sales Analysis Product Category"
Else
' Empty the entire sheet
'ws.UsedRange.ClearContents
End If
' Write headers
With ws.Rows(TOP_ROW)
.Cells(1).Value = "Sales Unit"
.Cells(3).Value = "Month"
End With
' Write month names
Set startCell = ws.Range("C11")
Dim monthNames() As Variant
monthNames = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
Dim i As Long
For i = LBound(monthNames) To UBound(monthNames)
startCell.Offset(0, i).Value = monthNames(i)
Next i
' Write headers
With ws.Rows(12)
.Cells(1).Value = "Product Category"
End With
' Write sub-column names
Set startCell = ws.Range("B12")
Dim subColumn() As Variant
subColumn = Array("Travel insurance", "Health insurance", "Life insurance", "Vehicle insurance", "Accident insurance", "Monthly Total", "Quaterly Total")
For sc = LBound(subColumn) To UBound(subColumn)
startCell.Offset(sc, 0).Value = subColumn(sc)
Next sc
Set startCell = ws.Range("C12")
For m = LBound(monthNames) To UBound(monthNames)
Dim int_quarter, int_month As Integer
int_month = m + 1
int_quarter = GetQuarterFromMonth(int_month)
startCell.Offset(0, m).Value = TravelInsuranceByMonth(int_month)
startCell.Offset(1, m).Value = HealthInsuranceByMonth(int_month)
startCell.Offset(2, m).Value = LifeInsuranceByMonth(int_month)
startCell.Offset(3, m).Value = VehicleInsuranceByMonth(int_month)
startCell.Offset(4, m).Value = AccidentInsuranceByMonth(int_month)
startCell.Offset(5, m).Value = MonthlyTotal(int_month)
startCell.Offset(6, m).Value = QuartelyTotal(int_quarter)
Next m
For i = 0 To 100
Range("A1").Offset(0, i).EntireColumn.AutoFit
Next i
For i = 2 To 14
Range("A1").Offset(0, i).EntireColumn.ColumnWidth = 10
Next i
Dim ranges_need_merge As Variant
ranges_need_merge = Array("C1:N1", "A3:A7", "C9:E9", "F9:H9", "I9:K9", "L9:N9")
For r = LBound(ranges_need_merge) To UBound(ranges_need_merge)
range_need_merge = ranges_need_merge(r)
With Range(range_need_merge)
.Merge
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
End With
Next r
Dim ranges_need_paint As Variant
ranges_need_paint = Array("A1", "C2:N2", "A3:A7", "B3:B8")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(182, 215, 168)
End With
Next r
Range("B9").Interior.Color = RGB(0, 255, 0)
ranges_need_merge = Array("C10:N10", "A12:A16", "C18:E18", "F18:H18", "I18:K18", "L18:N18")
For r = LBound(ranges_need_merge) To UBound(ranges_need_merge)
range_need_merge = ranges_need_merge(r)
With Range(range_need_merge)
.Merge
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
End With
Next r
' Set background color for specific ranges
ranges_need_paint = Array("A10", "C11:N11", "A12:A16", "B12:B17")
For r = LBound(ranges_need_paint) To UBound(ranges_need_paint)
range_need_merge = ranges_need_paint(r)
With Range(range_need_merge)
.Interior.Color = RGB(164, 194, 244)
End With
Next r
' Highlight total row
Range("B18").Interior.Color = RGB(0, 255, 255)
End Function

3
task4/1/ThisWorkbook.cls Normal file
View File

@@ -0,0 +1,3 @@
Option Explicit

132
task4/1/Var.bas Normal file
View File

@@ -0,0 +1,132 @@
Attribute VB_Name = "Var"
Option Explicit
' Set the maximum number of sales to 100
Global Const MAX_NUM_OF_SALES = 100
' Arrays to store user details (usernames, passwords, teams, ages)
' Each user's details are stored in a corresponding index of the arrays
Global usernames(100) As String ' Array to store usernames of users
Global passwords(100) As String ' Array to store passwords of users
Global teams(100) As String ' Array to store teams of users
Global ages(100) As String ' Array to store ages of users
' for calculation
' Global arrays to store sales data for each agent for each month
' monthly_sales(agent_index, month_index) stores the sales data for a particular agent in a particular month
' MAX_NUM_OF_SALES is the maximum number of agents, 12 is the maximum number of months
Global monthly_sales(MAX_NUM_OF_SALES, 12) As Double ' Array to store sales data for each agent for each month
' Global variables to store file path and workbook objects for each workbook
' agentSalesFilePath stores the path of the Agent Sales workbook
' agentSalesFileOK stores whether the Agent Sales workbook was successfully opened or not
' agent_sales_workbook and agent_sales_worksheet store the workbook and worksheet objects of the Agent Sales workbook
Global agentSalesFilePath As String ' String to store the path of the Agent Sales workbook
Global agent_sales_workbook As Workbook ' Workbook object for the Agent Sales workbook
Global agent_sales_worksheet As Worksheet ' Worksheet object for the Agent Sales workbook
Global agent_sales_file_OK As Boolean ' Boolean to store whether the Agent Sales workbook was successfully opened or not
' Similar comments apply to agent_working_performance_workbook, agent_working_performance_worksheet, agent_working_performance_OK, agentWorkingPerformancePath, product_sales_workbook, product_sales_worksheet, product_sales_OK, and productSalesPath
Global agent_working_performance_workbook As Workbook ' Workbook object for the Agent Working Performance workbook
Global agent_working_performance_worksheet As Worksheet ' Worksheet object for the Agent Working Performance workbook
Global agent_working_performance_OK As Boolean ' Boolean to store whether the Agent Working Performance workbook was successfully opened or not
Global agentWorkingPerformancePath As String ' String to store the path of the Agent Working Performance workbook
Global product_sales_workbook As Workbook ' Workbook object for the Product Sales workbook
Global product_sales_worksheet As Worksheet ' Worksheet object for the Product Sales workbook
Global product_sales_OK As Boolean ' Boolean to store whether the Product Sales workbook was successfully opened or not
Global productSalesPath As String ' String to store the path of the Product Sales workbook
' Arrays to store data for each agent and month for agent performance analysis
Global AgentPerformanceAnalysisHelloworld As String ' String to store an item of analysis for agent performance
Global AgentPerformanceAnalysisRankOfEachMonth(12, 5) As String ' Array to store the rank of each month for agent performance
Global TempMonthlyComission(12) As String ' Array to store temporary monthly commission
Global SortedMonthlyComission(12) As Double ' Array to store sorted monthly commission
' Array to store sorted array and sort result
Global sortedArray As Variant ' Array to store sorted array
Global sort_result As Variant ' Variant to store sort result
' config
' Global variables to store the column numbers for each field in the sales analysis sheet
' These constants are used to easily reference each column's number in the sales analysis sheet
Global NumOfSales As Integer ' Variable to store the number of sales
Global SALES_ANALYSIS_COL_MONTH As String ' Column number for Month in the sales analysis sheet
Global SALES_ANALYSIS_COL_QUARTER As String ' Column number for Quarter in the sales analysis sheet
Global SALES_ANALYSIS_COL_PRODUCT_CATEGORY As String ' Column number for Product Category in the sales analysis sheet
Global SALES_ANALYSIS_COL_SELLING_UNIT As String ' Column number for Selling Unit in the sales analysis sheet
Global SALES_ANALYSIS_COL_MONTHLY_SALES As String ' Column number for Monthly Sales in the sales analysis sheet
Global SALES_ANALYSIS_COL_QUARTELY_SALES As String ' Column number for Quarterly Sales in the sales analysis sheet
Global SALES_ANALYSIS_COL_COMMISSION As String ' Column number for Commission in the sales analysis sheet
Global SALES_ANALYSIS_COL_MONTHLY_MARGIN As String ' Column number for Monthly Margin in the sales analysis sheet
Global SALES_ANALYSIS_COL_QUATERLY_MARGIN As String ' Column number for Quarterly Margin in the sales analysis sheet
Global SALES_ANALYSIS_COL_QUATERLY_COMMISSION_ As String ' Column number for Quarterly Commission in the sales analysis sheet
'row
' Global constants to store the row numbers for each month in the sales analysis sheet
' These constants are used to easily reference each month's row in the sales analysis sheet
Global SALES_ANALYSIS_ROW_JANUARY As String ' Row number for January in the sales analysis sheet
Global SALES_ANALYSIS_ROW_FEBURARY As String ' Row number for February in the sales analysis sheet
Global SALES_ANALYSIS_ROW_MARCH As String ' Row number for March in the sales analysis sheet
Global SALES_ANALYSIS_ROW_APRIL As String ' Row number for April in the sales analysis sheet
Global SALES_ANALYSIS_ROW_MAY As String ' Row number for May in the sales analysis sheet
Global SALES_ANALYSIS_ROW_JUNE As String ' Row number for June in the sales analysis sheet
Global SALES_ANALYSIS_ROW_JULY As String ' Row number for July in the sales analysis sheet
Global SALES_ANALYSIS_ROW_AUGEST As String ' Row number for August in the sales analysis sheet
Global SALES_ANALYSIS_ROW_SEPTEMBER As String ' Row number for September in the sales analysis sheet
Global SALES_ANALYSIS_ROW_OCTOBER As String ' Row number for October in the sales analysis sheet
Global SALES_ANALYSIS_ROW_NOVEMBER As String ' Row number for November in the sales analysis sheet
Global SALES_ANALYSIS_ROW_DECEMBER As String ' Row number for December in the sales analysis sheet
' Global variables to store meta data for each month of sales per agent
' Array to store sales data per agent for each month
Global SALES_ARRAY As Variant
' Objects to store sales data per agent for each month
Global monthly_commission_per_agent As Object ' Object to store monthly commission per agent
Global monthly_product_sales_selling_unit_per_agent As Object ' Object to store monthly product sales selling unit per agent
Global monthly_product_sales_selling_price_per_agent As Object ' Object to store monthly product sales selling price per agent
Global monthly_product_sales_per_agent As Object ' Object to store monthly product sales per agent
' Global constant to store the string separator for concatenation
Global STRING_SEPERATOR As String ' String separator for concatenation
' Global constant to store the array of month names
Global MONTH_NAMES As Variant ' Array to store month names
' NoOfCasesTable
' Objects to store data about new and collapsed cases per agent
Global new_case_per_agent As Object ' Object to store data about new cases per agent
Global collapsed_case_per_agent As Object ' Object to store data about collapsed cases per agent
' Variables to store data about new and collapsed cases per team
Global new_case_team_a As Double ' Variable to store data about new cases for team A
Global collapsed_case_team_a As Double ' Variable to store data about collapsed cases for team A
Global new_case_team_b As Double ' Variable to store data about new cases for team B
Global collapsed_case_team_b As Double ' Variable to store data about collapsed cases for team B
' Object to store data about case persistency per agent
Global case_persistency_by_agent As Object ' Object to store data about case persistency per agent
Global output_report_directory As String
' calculation
' Arrays to store meta data of each workbook
Global AgentSalesMeta As Variant ' Meta data of Agent Sales workbook
Global ProductSalesMeta As Variant ' Meta data of Product Sales workbook
Global AgentWorkingPerformanceMeta As Variant ' Meta data of Agent Working Performance workbook
Global CombinedSalesMeta As Variant ' Meta data of Combined Sales workbook
' Global constants to store color codes for status
Global STATUS_COLOR_GREEN As String ' Color code for green status
Global STATUS_COLOR_YELLOW As String ' Color code for yellow status
Global STATUS_COLOR_RED As String ' Color code for red status

View File

@@ -0,0 +1,177 @@
Attribute VB_Name = "as_xlsx_get_agent_monthly_sale"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim SalesNewCaseByMonth As Integer
Dim SalesCollapsedCaseByMonth As Integer
Dim i, j As Integer
' variable for result
Dim monthly_total_sell, month_total_commission
Set monthly_total_sell = CreateObject("Scripting.Dictionary")
Set month_total_commission = CreateObject("Scripting.Dictionary")
Dim team_a_best, team_a_best_value, team_a_best_name, team_a_best_commission
Set team_a_best = CreateObject("Scripting.Dictionary")
Set team_a_best_value = CreateObject("Scripting.Dictionary")
Set team_a_best_name = CreateObject("Scripting.Dictionary")
Set team_a_best_commission = CreateObject("Scripting.Dictionary")
Dim team_b_best, team_b_best_value, team_b_best_name, team_b_best_commission
Set team_b_best = CreateObject("Scripting.Dictionary")
Set team_b_best_value = CreateObject("Scripting.Dictionary")
Set team_b_best_name = CreateObject("Scripting.Dictionary")
Set team_b_best_commission = CreateObject("Scripting.Dictionary")
For j = 1 To 12
team_a_best(CStr(j)) = 0
team_b_best(CStr(j)) = 0
Next j
For i = start_row To last_row
Dim date_value As String
Dim agent_name As String
Dim team As String
Dim temp_key As String
Dim selling_price, commision_pct, commision_value As Double
Dim int_month, int_quarter As Integer
date_value = ReadCellValue("B" & CStr(i))
int_month = GetMonthFrDate(date_value)
int_quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("C" & CStr(i))
team = ReadCellValue("D" & CStr(i))
selling_price = CDbl(ReadCellValue("E" & CStr(i)))
commision_pct = CDbl(ReadCellValue("F" & CStr(i)))
commision_value = selling_price * commision_pct
temp_key = agent_name & "," & int_month
' create if not found agent_name
If (Not (IsEmpty(temp_key)) And Not (monthly_total_sell.exists(temp_key))) Then
For j = 1 To 12
monthly_total_sell(agent_name + "," + CStr(j)) = 0
Next j
End If
monthly_total_sell(agent_name + "," + CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month)) + selling_price
month_total_commission(agent_name + "," + CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month)) + commision_value
Next i
CountFigures = Array(monthly_total_sell, month_total_commission)
End Function
Function Run(ws As Worksheet)
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
count_figures_result = CountFigures(ws, start_row, last_row)
Run = count_figures_result
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = as_xlsx_get_agent_monthly_sale.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Test()
Dim result As Variant
result = as_xlsx_get_agent_monthly_sale.OpenFile("c:\Temp\xlsx\Agent_Sales.xlsx")
Dim monthly_total_sell, month_total_commission
Set monthly_total_sell = result(0)
Set month_total_commission = result(1)
Debug.Print (monthly_total_sell("Eason,1"))
Debug.Print (month_total_commission("Eason,1"))
Debug.Print "done"
End Sub
Sub Helloworld()
Debug.Print "helloworld"
End Sub

View File

@@ -0,0 +1,201 @@
Attribute VB_Name = "as_xlsx_get_month_best_agent"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim SalesNewCaseByMonth As Integer
Dim SalesCollapsedCaseByMonth As Integer
Dim i, j As Integer
' variable for result
Dim monthly_total_sell, month_total_commission
Set monthly_total_sell = CreateObject("Scripting.Dictionary")
Set month_total_commission = CreateObject("Scripting.Dictionary")
Dim team_a_best, team_a_best_value, team_a_best_name, team_a_best_commission
Set team_a_best = CreateObject("Scripting.Dictionary")
Set team_a_best_value = CreateObject("Scripting.Dictionary")
Set team_a_best_name = CreateObject("Scripting.Dictionary")
Set team_a_best_commission = CreateObject("Scripting.Dictionary")
Dim team_b_best, team_b_best_value, team_b_best_name, team_b_best_commission
Set team_b_best = CreateObject("Scripting.Dictionary")
Set team_b_best_value = CreateObject("Scripting.Dictionary")
Set team_b_best_name = CreateObject("Scripting.Dictionary")
Set team_b_best_commission = CreateObject("Scripting.Dictionary")
For j = 1 To 12
team_a_best(CStr(j)) = 0
team_b_best(CStr(j)) = 0
Next j
For i = start_row To last_row
Dim date_value As String
Dim agent_name As String
Dim team As String
Dim temp_key As String
Dim selling_price, commision_pct, commision_value As Double
Dim int_month, int_quarter As Integer
date_value = ReadCellValue("B" & CStr(i))
int_month = GetMonthFrDate(date_value)
int_quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("C" & CStr(i))
team = ReadCellValue("D" & CStr(i))
selling_price = CDbl(ReadCellValue("E" & CStr(i)))
commision_pct = CDbl(ReadCellValue("F" & CStr(i)))
commision_value = selling_price * commision_pct
temp_key = agent_name & "," & int_month
' create if not found agent_name
If (Not (IsEmpty(temp_key)) And Not (monthly_total_sell.exists(temp_key))) Then
For j = 1 To 12
monthly_total_sell(agent_name + "," + CStr(j)) = 0
Next j
End If
monthly_total_sell(agent_name + "," + CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month)) + selling_price
month_total_commission(agent_name + "," + CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month)) + commision_value
' is in team A?
If (team = "A") Then
If (monthly_total_sell(agent_name + "," + CStr(int_month)) > team_a_best(CStr(int_month))) Then
team_a_best_name(CStr(int_month)) = agent_name
team_a_best_value(CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month))
team_a_best_commission(CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month))
End If
End If
' is in team B?
If (team = "B") Then
If (monthly_total_sell(agent_name + "," + CStr(int_month)) > team_b_best(CStr(int_month))) Then
team_b_best_name(CStr(int_month)) = agent_name
team_b_best_value(CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month))
team_b_best_commission(CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month))
End If
End If
Next i
CountFigures = Array(monthly_total_sell, _
team_a_best_name, _
team_a_best_value, _
team_a_best_commission, _
team_b_best_name, _
team_b_best_value, _
team_b_best_commission _
)
End Function
Function Run(ws As Worksheet)
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
count_figures_result = CountFigures(ws, start_row, last_row)
Run = count_figures_result
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = as_xlsx_get_month_best_agent.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Test()
Dim result As Variant
Dim result1
result = as_xlsx_get_month_best_agent.OpenFile("c:\Temp\xlsx\Agent_Sales.xlsx")
Set result1 = result(0)
Debug.Print "done"
End Sub
Sub Helloworld()
Debug.Print "helloworld"
End Sub

View File

@@ -0,0 +1,171 @@
Attribute VB_Name = "as_xlsx_get_team_monthly_sale"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim SalesNewCaseByMonth As Integer
Dim SalesCollapsedCaseByMonth As Integer
Dim i, j As Integer
' variable for result
Dim monthly_total_sell, month_total_commission
Set monthly_total_sell = CreateObject("Scripting.Dictionary")
Set month_total_commission = CreateObject("Scripting.Dictionary")
Dim teams_month_total_sale
Set teams_month_total_sale = CreateObject("Scripting.Dictionary")
Dim team_a_month_total_sale
Set team_a_month_total_sale = CreateObject("Scripting.Dictionary")
Dim team_b_month_total_sale
Set team_b_month_total_sale = CreateObject("Scripting.Dictionary")
For j = 1 To 12
team_a_month_total_sale(CStr(j)) = 0
team_b_month_total_sale(CStr(j)) = 0
Next j
For i = start_row To last_row
Dim date_value As String
Dim agent_name As String
Dim team As String
Dim temp_key As String
Dim selling_price, commision_pct, commision_value As Double
Dim int_month, int_quarter As Integer
date_value = ReadCellValue("B" & CStr(i))
int_month = GetMonthFrDate(date_value)
int_quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("C" & CStr(i))
team = ReadCellValue("D" & CStr(i))
selling_price = CDbl(ReadCellValue("E" & CStr(i)))
' commision_pct = CDbl(ReadCellValue("F" & CStr(i)))
' commision_value = selling_price * commision_pct
If (team = "A") Then
team_a_month_total_sale(CStr(int_month)) = team_a_month_total_sale(CStr(int_month)) + selling_price
End If
If (team = "B") Then
team_b_month_total_sale(CStr(int_month)) = team_b_month_total_sale(CStr(int_month)) + selling_price
End If
teams_month_total_sale(CStr(int_month)) = team_a_month_total_sale(CStr(int_month)) + team_b_month_total_sale(CStr(int_month))
Next i
CountFigures = Array(teams_month_total_sale, team_a_month_total_sale, team_b_month_total_sale)
End Function
Function Run(ws As Worksheet)
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
count_figures_result = CountFigures(ws, start_row, last_row)
Run = count_figures_result
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = as_xlsx_get_team_monthly_sale.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Test()
Dim result As Variant
result = as_xlsx_get_team_monthly_sale.OpenFile("c:\Temp\xlsx\Agent_Sales.xlsx")
Dim teams_month_total_sale, team_a_month_total_sale, team_b_month_total_sale
Set teams_month_total_sale = result(0)
Set team_a_month_total_sale = result(1)
Set team_b_month_total_sale = result(2)
Debug.Print (teams_month_total_sale("1"))
Debug.Print (team_a_month_total_sale("1"))
Debug.Print "done"
End Sub
Sub Helloworld()
Debug.Print "helloworld"
End Sub

View File

@@ -0,0 +1,199 @@
Attribute VB_Name = "as_xlsx_helloworld_pivot"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim SalesNewCaseByMonth As Integer
Dim SalesCollapsedCaseByMonth As Integer
Dim i, j As Integer
' variable for result
Dim monthly_total_sell, month_total_commission
Set monthly_total_sell = CreateObject("Scripting.Dictionary")
Set month_total_commission = CreateObject("Scripting.Dictionary")
Dim team_a_best, team_a_best_value, team_a_best_name, team_a_best_commission
Set team_a_best = CreateObject("Scripting.Dictionary")
Set team_a_best_value = CreateObject("Scripting.Dictionary")
Set team_a_best_name = CreateObject("Scripting.Dictionary")
Set team_a_best_commission = CreateObject("Scripting.Dictionary")
Dim team_b_best, team_b_best_value, team_b_best_name, team_b_best_commission
Set team_b_best = CreateObject("Scripting.Dictionary")
Set team_b_best_value = CreateObject("Scripting.Dictionary")
Set team_b_best_name = CreateObject("Scripting.Dictionary")
Set team_b_best_commission = CreateObject("Scripting.Dictionary")
For j = 1 To 12
team_a_best(CStr(j)) = 0
team_b_best(CStr(j)) = 0
Next j
For i = start_row To last_row
Dim date_value As String
Dim agent_name As String
Dim team As String
Dim temp_key As String
Dim selling_price, commision_pct, commision_value As Double
Dim int_month, int_quarter As Integer
date_value = ReadCellValue("B" & CStr(i))
int_month = GetMonthFrDate(date_value)
int_quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("C" & CStr(i))
team = ReadCellValue("D" & CStr(i))
selling_price = CDbl(ReadCellValue("E" & CStr(i)))
commision_pct = CDbl(ReadCellValue("F" & CStr(i)))
commision_value = selling_price * commision_pct
temp_key = agent_name & "," & int_month
' create if not found agent_name
If (Not (IsEmpty(temp_key)) And Not (monthly_total_sell.exists(temp_key))) Then
For j = 1 To 12
monthly_total_sell(agent_name + "," + CStr(j)) = 0
Next j
End If
monthly_total_sell(agent_name + "," + CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month)) + selling_price
month_total_commission(agent_name + "," + CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month)) + commision_value
' is in team A?
If (CheckSalesIsInTeamA(agent_name)) Then
If (monthly_total_sell(agent_name + "," + CStr(int_month)) > team_a_best(CStr(int_month))) Then
team_a_best_name(CStr(int_month)) = agent_name
team_a_best_value(CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month))
team_a_best_commission(CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month))
End If
End If
' is in team B?
If (CheckSalesIsInTeamB(agent_name)) Then
If (monthly_total_sell(agent_name + "," + CStr(int_month)) > team_b_best(CStr(int_month))) Then
team_b_best_name(CStr(int_month)) = agent_name
team_b_best_value(CStr(int_month)) = monthly_total_sell(agent_name + "," + CStr(int_month))
team_b_best_commission(CStr(int_month)) = month_total_commission(agent_name + "," + CStr(int_month))
End If
End If
Next i
CountFigures = Array(monthly_total_sell, _
team_a_best_name, _
team_a_best_value, _
team_a_best_commission, _
team_b_best_name, _
team_b_best_value, _
team_b_best_commission _
)
End Function
Function Run(ws As Worksheet)
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
count_figures_result = CountFigures(ws, start_row, last_row)
Run = count_figures_result
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = as_xlsx_helloworld_pivot.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Test()
Dim result As Variant
Dim result1
result = as_xlsx_helloworld_pivot.OpenFile("c:\Temp\xlsx\Agent_Sales.xlsx")
Set result1 = result(0)
Debug.Print "done"
End Sub
Sub Helloworld()
Debug.Print "helloworld"
End Sub

View File

@@ -0,0 +1,204 @@
Attribute VB_Name = "awp_xlsx_case_persistency_pivot"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function CountFigures(ws As Worksheet, ByVal start_row As Integer, ByVal last_row As Integer)
Dim i, j As Integer
' variable for result
Dim agent_month_new_case, agent_month_collapsed_case
Set agent_month_new_case = CreateObject("Scripting.Dictionary")
Set agent_month_collapsed_case = CreateObject("Scripting.Dictionary")
Dim agent_quarter_new_case, agent_quarter_collapsed_case
Set agent_quarter_new_case = CreateObject("Scripting.Dictionary")
Set agent_quarter_collapsed_case = CreateObject("Scripting.Dictionary")
Dim agent_month_case_persistency, agent_quarter_case_persistency
Set agent_month_case_persistency = CreateObject("Scripting.Dictionary")
Set agent_quarter_case_persistency = CreateObject("Scripting.Dictionary")
For i = start_row To last_row
Dim date_value As String
Dim int_month, quarter As Integer
Dim agent_name, new_case, collapsed_case, agent_team As String
Dim agent_quarter_key, agent_month_key, temp_key As String
date_value = ReadCellValue("A" & CStr(i))
int_month = GetMonthFrDate(date_value)
quarter = GetQuarterFrDate(date_value)
agent_name = ReadCellValue("B" & CStr(i))
agent_team = ReadCellValue("C" & CStr(i))
new_case = ReadCellValue("D" & CStr(i))
collapsed_case = ReadCellValue("E" & CStr(i))
agent_month_key = agent_name + "," + CStr(int_month)
agent_quarter_key = agent_name + "," + CStr(quarter)
' create if not found agent_name
If (Not (IsEmpty(agent_month_key)) And Not (agent_month_new_case.exists(agent_month_key))) Then
For j = 1 To 12
agent_month_new_case(agent_name + "," + CStr(j)) = 0
agent_month_collapsed_case(agent_name + "," + CStr(j)) = 0
agent_month_case_persistency(agent_name + "," + CStr(j)) = 0
Next j
For j = 1 To 4
agent_quarter_new_case(agent_name + "," + CStr(j)) = 0
agent_quarter_collapsed_case(agent_name + "," + CStr(j)) = 0
agent_quarter_case_persistency(agent_name + "," + CStr(j)) = 0
Next j
End If
If (new_case <> "") Then
agent_month_new_case(agent_month_key) = agent_month_new_case(agent_month_key) + CInt(new_case)
agent_quarter_new_case(agent_quarter_key) = agent_quarter_new_case(agent_quarter_key) + CInt(new_case)
End If
If (collapsed_case <> "") Then
agent_month_collapsed_case(agent_month_key) = agent_month_collapsed_case(agent_month_key) + CInt(collapsed_case)
agent_quarter_collapsed_case(agent_quarter_key) = agent_quarter_collapsed_case(agent_quarter_key) + CInt(collapsed_case)
End If
If (agent_month_new_case(agent_month_key) > 0) Then
agent_month_case_persistency(agent_month_key) = agent_month_new_case(agent_month_key) / (agent_month_new_case(agent_month_key) + agent_month_collapsed_case(agent_quarter_key))
Else
agent_month_case_persistency(agent_month_key) = 0
End If
If (agent_quarter_case_persistency(agent_month_key) > 0) Then
agent_quarter_case_persistency(agent_quarter_key) = agent_quarter_new_case(agent_quarter_key) / (agent_quarter_new_case(agent_quarter_key) + agent_quarter_collapsed_case(agent_quarter_key))
Else
agent_quarter_case_persistency(agent_month_key) = 0
End If
Next i
CountFigures = Array(agent_month_new_case, agent_month_collapsed_case, _
agent_quarter_new_case, agent_quarter_collapsed_case, _
agent_month_case_persistency, agent_quarter_case_persistency)
End Function
Function Run(ws As Worksheet)
Dim row_count As Integer
Dim rw As Variant
Dim count_figures_result As Variant
Dim start_row, last_row As Integer
start_row = 2
last_row = getLastRow(start_row)
Run = CountFigures(ws, start_row, last_row)
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
' wb.Windows(1).Visible = False
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = awp_xlsx_case_persistency_pivot.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Test()
Dim result As Variant
Dim agent_month_new_case, agent_month_collapsed_case, agent_quarter_new_case, agent_quarter_collapsed_case, agent_month_case_persistency, agent_quarter_case_persistency
result = awp_xlsx_case_persistency_pivot.OpenFile("c:\Temp\xlsx\Agent_Working_Performance.xlsx")
Set agent_month_new_case = result(0)
Set agent_month_collapsed_case = result(1)
Set agent_quarter_new_case = result(2)
Set agent_quarter_collapsed_case = result(3)
Set agent_month_case_persistency = result(4)
Set agent_quarter_case_persistency = result(5)
Debug.Print agent_month_case_persistency("Eason,1")
Debug.Print agent_month_case_persistency("Eason,2")
Debug.Print "done"
End Sub
Sub Helloworld()
Debug.Print "helloworld"
End Sub

View File

@@ -0,0 +1,102 @@
Attribute VB_Name = "awp_xlsx_helloworld_pivot"
Option Explicit
' get the last row for a given xls sheet
Function getLastRow(ByVal start_row As Integer)
Dim last_row As Boolean
Dim last_check_row As Integer
Dim scan_row As Integer
Dim i As Integer
Dim cell_value_1 As String
Dim next_row_1 As Integer
scan_row = start_row
last_check_row = 9999
For i = start_row To last_check_row
scan_row = i
last_row = True
next_row_1 = i + 1
cell_value_1 = ReadCellValue("A" & CStr(next_row_1))
If (cell_value_1 <> "") Then
last_row = False
End If
If (last_row = True) Then
'Debug.Print "last row found"
Exit For
End If
Next i
getLastRow = scan_row
End Function
' get the value from cell for a given address
Function ReadCellValue(cell_addr As String)
ReadCellValue = Worksheets("Sheet1").Range(cell_addr).Value
End Function
' get the integer month from date
Function GetMonthFrDate(ByVal date_string As String) As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetMonthFrDate = intMonth
End Function
' get the integer quarter from date
Function GetQuarterFrDate(ByVal date_string As String) As Integer
Dim intQuarter As Integer
Dim intMonth As Integer
Dim dt As String
dt = DateValue(date_string)
intMonth = month(dt)
GetQuarterFrDate = Int((intMonth - 1) / 3) + 1
End Function
Function Run(ws As Worksheet)
Dim row_count As Integer
Dim rw As Variant
Run = Array(1, 2, 3, 4, 5, 6, 7, 8)
End Function
' canned method to open excel file
Function OpenFile(sPath As String)
Dim wb As Workbook
Set wb = Workbooks.Open(sPath)
wb.Windows(1).Visible = False
Dim count_figures_result As Variant
If Not (wb.Sheets("Sheet1") Is Nothing) Then
count_figures_result = awp_xlsx_helloworld_pivot.Run(wb.Sheets("Sheet1"))
End If
OpenFile = count_figures_result
wb.Close savechanges:=False
End Function
Sub Test()
awp_xlsx_helloworld_pivot.OpenFile ("c:\Temp\xlsx\Agent_Working_Performance.xlsx")
Debug.Print "done"
End Sub
Sub Helloworld()
Debug.Print "helloworld"
End Sub

9
task4/1/dev.bat Normal file
View File

@@ -0,0 +1,9 @@
@REM rm *.bas
@REM rm *.frm
@REM rm *.frx
@REM timeout 1
:loop
xlwings vba edit --file .\main.xlsm
timeout /t 1
goto loop

64
task4/1/frmLogin.frm Normal file
View File

@@ -0,0 +1,64 @@
VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} frmLogin
Caption = "Login"
ClientHeight = 7200
ClientLeft = 120
ClientTop = 465
ClientWidth = 5700
OleObjectBlob = "frmLogin.frx":0000
StartUpPosition = 1 'CenterOwner
End
Attribute VB_Name = "frmLogin"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim i As Integer
Dim j As Integer
Dim k As Integer
Private Sub cmdExitLogin_Click()
End
End Sub
Private Sub cmdLogin_Click()
Dim username_found As Boolean
username_found = False
' currently 100 users is good enough
For i = 1 To 100
If (txtUsername.Text = usernames(i)) Then
If (txtPassword.Text = passwords(i)) Then
' login success, show main form
frmLogin.Hide
frmMain.Show
username_found = True
End If
End If
Next i
If (username_found = False) Then
' login fail, show error message
MsgBox "sorry but username and password wrong"
End If
End Sub
Private Sub UserForm_Initialize()
Debug.Print "start"
Common.initAccountFromAccountSheet
Debug.Print "init account list done"
Config.init
Debug.Print "config init done"
End Sub

BIN
task4/1/frmLogin.frx Normal file

Binary file not shown.

545
task4/1/frmMain.frm Normal file
View File

@@ -0,0 +1,545 @@
VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} frmMain
Caption = "Main"
ClientHeight = 9255.001
ClientLeft = 120
ClientTop = 465
ClientWidth = 8655.001
OleObjectBlob = "frmMain.frx":0000
StartUpPosition = 1 'CenterOwner
End
Attribute VB_Name = "frmMain"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim monthly_commission As Variant
Dim montyly_commission_TA As Variant
Dim montyly_commission_TB As Variant
Dim quartely_commission_TA As Variant
Dim quartely_commission_TB As Variant
Dim monthly_top_5_comission_name As Variant
Dim monthly_top_5_comission_value As Variant
Dim monthly_total As Variant
Dim monthly_total_TA As Variant
Dim monthly_total_TB As Variant
Dim month_selected As Integer
Dim sales_selected As String
Dim sales_data_loaded As Boolean
Dim calc_result_empty As Boolean
Dim pivot_result
Dim get_team_monthly_sale
Dim teams_month_total_sale, team_a_month_total_sale, team_b_month_total_sale
Dim best_selling_result
Dim month_best_agent
Dim team_a_best_name, team_a_best_value, team_a_best_commission
Dim team_b_best_name, team_b_best_value, team_b_best_commission
Dim apanalysis_calc_result As Variant
Dim apanalysis_sales_calc_result As Variant
Dim agent_name_selected As String
Dim str_month_selected As String
Dim name_and_month As String
Dim case_persistency_pivot As Variant
Dim agent_month_new_case, agent_month_collapsed_case, agent_quarter_new_case, agent_quarter_collapsed_case, agent_month_case_persistency, agent_quarter_case_persistency
Dim agent_monthly_sale As Variant
Dim monthly_total_sell, month_total_commission
Function validateAgentSalesFile(workfile_xls_filename As String) As Boolean
Dim validation_result As Boolean
validation_result = True
Set agent_sales_workbook = Workbooks.Open(workfile_xls_filename)
Set agent_sales_worksheet = agent_sales_workbook.Worksheets(1)
If (agent_sales_worksheet.Cells(1, 1) <> "Sales No.") Then
validation_result = False
End If
If (agent_sales_worksheet.Cells(1, 2) <> "Date") Then
validation_result = False
End If
If (agent_sales_worksheet.Cells(1, 3) <> "Agent Name") Then
validation_result = False
End If
agent_sales_workbook.Close
validateAgentSalesFile = validation_result
End Function
Function validateAgentWorkingPerformanceFile(workfile_xls_filename As String) As Boolean
Dim validation_result As Boolean
validation_result = True
Set agent_working_performance_workbook = Workbooks.Open(workfile_xls_filename)
Set agent_working_performance_worksheet = agent_working_performance_workbook.Worksheets(1)
If (agent_working_performance_worksheet.Cells(1, 1) <> "Date") Then
validation_result = False
End If
If (agent_working_performance_worksheet.Cells(1, 2) <> "Name") Then
validation_result = False
End If
If (agent_working_performance_worksheet.Cells(1, 3) <> "Team") Then
validation_result = False
End If
agent_working_performance_workbook.Close savechanges:=False
validateAgentWorkingPerformanceFile = True
End Function
Function validateProductSalesFile(workfile_xls_filename As String) As Boolean
Dim validation_result As Boolean
validation_result = True
Set product_sales_workbook = Workbooks.Open(workfile_xls_filename)
Set product_sales_worksheet = product_sales_workbook.Worksheets(1)
If (product_sales_worksheet.Cells(1, 1) <> "Sales No.") Then
validation_result = False
End If
If (product_sales_worksheet.Cells(1, 2) <> "Date") Then
validation_result = False
End If
If (product_sales_worksheet.Cells(1, 3) <> "Product Category") Then
validation_result = False
End If
product_sales_workbook.Close
validateProductSalesFile = True
End Function
Private Sub cmbMonthSelect_Change()
If (cmbMonthSelect.Value <> "") Then
str_month_selected = Common.ConvLetterMonthToIntMonth(cmbMonthSelect.Value)
If (calc_result_empty = False) Then
name_and_month = agent_name_selected & "," & str_month_selected
frmMain.UpdateScreen
End If
End If
End Sub
Sub UpdateScreen()
' team details
Dim team_a_agent_name, team_b_agent_name As String
team_a_agent_name = team_a_best_name(str_month_selected)
team_b_agent_name = team_b_best_name(str_month_selected)
lblTotalSales.Caption = "Total Sales: " & " " & Format(teams_month_total_sale(str_month_selected), "0.00")
lblMonthlyCommissionTA.Caption = "Team A: " & "$" & Format(team_a_month_total_sale(str_month_selected), "0.00")
lblMonthlyCommissionTB.Caption = "Team B: " & "$" & Format(team_b_month_total_sale(str_month_selected), "0.00")
lblTaTopSeller.Caption = team_a_agent_name
lblTbTopSeller.Caption = team_b_agent_name
'commission
lblTaTopSellingUnit.Caption = Format(team_a_best_commission(str_month_selected), "0.00")
lblTbTopSellingUnit.Caption = Format(team_b_best_commission(str_month_selected), "0.00")
lblTaTopMonthlySales.Caption = Format(team_a_best_value(str_month_selected), "0.00")
lblTbTopMonthlySales.Caption = Format(team_b_best_value(str_month_selected), "0.00")
lblTaCasePersistency.Caption = Format(agent_month_case_persistency(team_a_agent_name & "," & str_month_selected), "0.00%")
lblTbCasePersistency.Caption = Format(agent_month_case_persistency(team_b_agent_name & "," & str_month_selected), "0.00%")
StatusTa.BackColor = Var.STATUS_COLOR_GREEN
If (agent_month_case_persistency(team_a_agent_name & "," & str_month_selected) < 0.66) Then
StatusTa.BackColor = Var.STATUS_COLOR_YELLOW
End If
If (agent_month_case_persistency(team_a_agent_name & "," & str_month_selected) < 0.33) Then
StatusTa.BackColor = Var.STATUS_COLOR_RED
End If
StatusTb.BackColor = Var.STATUS_COLOR_GREEN
If (agent_month_case_persistency(team_b_agent_name & "," & str_month_selected) < 0.66) Then
StatusTb.BackColor = Var.STATUS_COLOR_YELLOW
End If
If (agent_month_case_persistency(team_b_agent_name & "," & str_month_selected) < 0.33) Then
StatusTb.BackColor = Var.STATUS_COLOR_RED
End If
' agent details
Common.initAccountFromAccountSheet
lblAgentName.Caption = agent_name_selected
lblAgentAge.Caption = Common.LookupAge(agent_name_selected)
lblAgentTeam.Caption = Common.LookupTeam(agent_name_selected)
lblCasePersistency.Caption = Format(agent_month_case_persistency(name_and_month), "0.00")
lblCollpasedCase.Caption = agent_month_collapsed_case(name_and_month)
lblNewCase.Caption = agent_month_new_case(name_and_month)
lblTotalComission.Caption = month_total_commission(name_and_month)
lblTotalSale.Caption = Format(monthly_total_sell(name_and_month), "0.00")
' check if path found
' handle throw error
If (Dir(Application.ActiveWorkbook.Path & "\images\" & agent_name_selected & ".jpg") = "") Then
Msgbox "Sorry but the path for staff profile image not found"
Else
Image1.Picture = LoadPicture(Application.ActiveWorkbook.Path & "\images\" & agent_name_selected & ".jpg")
End If
End Sub
Private Sub cmbAgentSelect_Change()
If (cmbAgentSelect.Value <> "") Then
agent_name_selected = cmbAgentSelect.Value
If (calc_result_empty = False) Then
'monthly_commission_per_agent
name_and_month = agent_name_selected & "," & str_month_selected
frmMain.UpdateScreen
End If
End If
End Sub
Private Sub cmdBrowseAgentSalesFileBtn_Click()
Dim validate_result As Boolean
Var.agentSalesFilePath = Application.GetOpenFilename(FileFilter:="Excel files (*.xlsx*), *.xlsx*", Title:="Choose an Excel file to open", MultiSelect:=False)
Debug.Print CStr(Var.agentSalesFilePath)
If CStr(Var.agentSalesFilePath) = CStr(False) Then
' User did not select a file
MsgBox "no file selected"
Else
' User selected a file
txtBrowseAgentSalesFilePath.Value = Var.agentSalesFilePath
validate_result = validateAgentSalesFile(Var.agentSalesFilePath)
If (validate_result = False) Then
MsgBox "sorry but wrong agent sales file selected"
Var.agentSalesFilePath = ""
txtBrowseAgentSalesFilePath.Text = ""
Else
Debug.Print "agent sales file validation OK"
Var.agent_sales_file_OK = True
End If
End If
End Sub
Sub UpdateSelectReportTabStatus()
Dim result As Boolean
result = False
If (Var.agent_sales_file_OK = True) Then
If (Var.agent_working_performance_OK = True) Then
If (Var.product_sales_OK = True) Then
MultiPage1.Pages(1).Enabled = True
MultiPage1.Pages(2).Enabled = True
End If
End If
End If
End Sub
Private Sub cmdBrowseAgentWorkingPerformanceBtn_Click()
Dim validate_result As Boolean
Var.agentWorkingPerformancePath = Application.GetOpenFilename(FileFilter:="Excel files (*.xlsx*), *.xlsx*", Title:="Choose an Excel file to open", MultiSelect:=False)
Debug.Print CStr(Var.agentWorkingPerformancePath)
If CStr(Var.agentWorkingPerformancePath) = CStr(False) Then
' User did not select a file
MsgBox "no file selected"
Else
' User selected a file
txtBrowseAgentWorkingPerformancePath.Value = Var.agentWorkingPerformancePath
validate_result = validateAgentWorkingPerformanceFile(Var.agentWorkingPerformancePath)
If (validate_result = False) Then
MsgBox "sorry but wrong agent sales file selected"
Var.agentWorkingPerformancePath = ""
txtBrowseAgentWorkingPerformancePath.Text = ""
Else
Debug.Print "agent sales file validation OK"
Var.agent_working_performance_OK = True
End If
End If
End Sub
Private Sub cmdBrowseProductSalesBtn_Click()
Dim validate_result As Boolean
Var.productSalesPath = Application.GetOpenFilename(FileFilter:="Excel files (*.xlsx*), *.xlsx*", Title:="Choose an Excel file to open", MultiSelect:=False)
If CStr(Var.productSalesPath) = CStr(False) Then
' User did not select a file
MsgBox "no file selected"
Else
' User selected a file
txtBrowseProductSalesPath.Value = Var.productSalesPath
validate_result = validateProductSalesFile(Var.productSalesPath)
If (validate_result = False) Then
MsgBox "sorry but wrong agent sales file selected"
Var.productSalesPath = ""
txtBrowseProductSalesPath.Text = ""
Else
Debug.Print "agent sales file validation OK"
Var.product_sales_OK = True
End If
End If
End Sub
Private Sub cmdCalculate_Click()
Dim sPath As String
Var.AgentSalesMeta = ReadAgentSalesWorkbook.Run(Var.agentSalesFilePath)
Var.ProductSalesMeta = ReadProductSalesWorkbook.Run(Var.productSalesPath)
Var.AgentWorkingPerformanceMeta = ReadAgentWorkingPerfWorkbook.Run(Var.agentWorkingPerformancePath)
Var.CombinedSalesMeta = Array(Var.AgentSalesMeta, Var.ProductSalesMeta, Var.AgentWorkingPerformanceMeta)
calc_result_empty = False
case_persistency_pivot = awp_xlsx_case_persistency_pivot.OpenFile(Var.agentWorkingPerformancePath)
Set agent_month_new_case = case_persistency_pivot(0)
Set agent_month_collapsed_case = case_persistency_pivot(1)
Set agent_quarter_new_case = case_persistency_pivot(2)
Set agent_quarter_collapsed_case = case_persistency_pivot(3)
Set agent_month_case_persistency = case_persistency_pivot(4)
Set agent_quarter_case_persistency = case_persistency_pivot(5)
agent_monthly_sale = as_xlsx_get_agent_monthly_sale.OpenFile(Var.agentSalesFilePath)
Set monthly_total_sell = agent_monthly_sale(0)
Set month_total_commission = agent_monthly_sale(1)
month_best_agent = as_xlsx_get_month_best_agent.OpenFile(Var.agentSalesFilePath)
'Set monthly_total_sell = month_best_agent(0)
Set team_a_best_name = month_best_agent(1)
Set team_a_best_value = month_best_agent(2)
Set team_a_best_commission = month_best_agent(3)
Set team_b_best_name = month_best_agent(4)
Set team_b_best_value = month_best_agent(5)
Set team_b_best_commission = month_best_agent(6)
month_best_agent = as_xlsx_get_team_monthly_sale.OpenFile(Var.agentSalesFilePath)
Set teams_month_total_sale = month_best_agent(0)
Set team_a_month_total_sale = month_best_agent(1)
Set team_b_month_total_sale = month_best_agent(2)
agent_name_selected = "Alex"
str_month_selected = "1"
name_and_month = "Alex,1"
frmMain.UpdateScreen
' APAnalysis_WriteTable calc_result, file_path, wb
cmbMonthSelect.Enabled = True
optTeamEnable.Enabled = True
optAgentEnable.Enabled = True
framePressToStart.Visible = False
frameTeamDetails.Visible = True
' wb.Save
' wb.Close
Debug.Print "done"
End Sub
Private Sub cmdLogout_Click()
frmMain.Hide
frmLogin.Show
End Sub
Private Sub cmdGenTextRpt_Click()
Debug.Print "GenTextReport start"
Common.GenTextReport
Debug.Print "GenTextReport end"
End Sub
Private Sub cmdTest_Click()
End Sub
Private Sub CommandButton11_Click()
End
End Sub
Function createNewXlsx(file_path As String)
Dim wb As Workbook
Set wb = Workbooks.Add
wb.SaveAs file_path
wb.Close
End Function
Private Sub UserForm_Initialize()
calc_result_empty = True
Config.init
'txtOutputRptDirectory.Text = Var.output_report_directory
frmMain.cmbGenRptType.AddItem "01 Text Report"
frmMain.cmbGenRptType.AddItem "02 Chart Report"
frmMain.cmbMonthSelect.AddItem "Jan"
frmMain.cmbMonthSelect.AddItem "Feb"
frmMain.cmbMonthSelect.AddItem "Mar"
frmMain.cmbMonthSelect.AddItem "Apr"
frmMain.cmbMonthSelect.AddItem "May"
frmMain.cmbMonthSelect.AddItem "Jun"
frmMain.cmbMonthSelect.AddItem "Jul"
frmMain.cmbMonthSelect.AddItem "Aug"
frmMain.cmbMonthSelect.AddItem "Sep"
frmMain.cmbMonthSelect.AddItem "Oct"
frmMain.cmbMonthSelect.AddItem "Nov"
frmMain.cmbMonthSelect.AddItem "Dec"
cmbMonthSelect.Value = "Jan"
frmMain.cmbAgentSelect.AddItem "Alex"
frmMain.cmbAgentSelect.AddItem "Ben"
frmMain.cmbAgentSelect.AddItem "Candy"
frmMain.cmbAgentSelect.AddItem "Danny"
frmMain.cmbAgentSelect.AddItem "Eason"
frmMain.cmbAgentSelect.AddItem "Filex"
frmMain.cmbAgentSelect.AddItem "Gary"
frmMain.cmbAgentSelect.AddItem "Henry"
frmMain.cmbAgentSelect.AddItem "Irene"
frmMain.cmbAgentSelect.AddItem "Jenny"
sales_selected = "Alex"
cmbAgentSelect.Text = ""
cmbAgentSelect.Value = sales_selected
cmbGenRptType.Text = ""
cmbGenRptType.Value = "01 Text Report"
framePressToStart.Visible = True
framePressToStart.Top = 75
framePressToStart.Left = 10
framePressToStart.Height = 283
framePressToStart.Width = 388
frameAgentDetails.Visible = False
frameAgentDetails.Top = framePressToStart.Top
frameAgentDetails.Left = framePressToStart.Left
frameAgentDetails.Height = framePressToStart.Height
frameAgentDetails.Width = framePressToStart.Width
frameTeamDetails.Visible = False
frameTeamDetails.Top = framePressToStart.Top
frameTeamDetails.Left = framePressToStart.Left
frameTeamDetails.Height = framePressToStart.Height
frameTeamDetails.Width = framePressToStart.Width
' align frame in tab 2
frmChartRpt.Top = frmTextReport.Top
frmChartRpt.Left = frmTextReport.Left
frmChartRpt.Height = frmTextReport.Height
frmChartRpt.Width = frmTextReport.Width
Var.STATUS_COLOR_GREEN = RGB(0, 128, 0)
Var.STATUS_COLOR_YELLOW = RGB(255, 255, 0)
Var.STATUS_COLOR_RED = RGB(255, 0, 0)
End Sub
Private Sub txtOutputRptDirectory_Change()
Var.output_report_directory = txtOutputRptDirectory.Text
End Sub
Private Sub cmdGenReport_Click()
If (frmMain.cmbGenRptType.Value = "01 Text Report") Then
Common.GenTextReport
End If
If (frmMain.cmbGenRptType.Value = "02 Chart Report") Then
Common.GenChartReport
End If
End Sub
Private Sub optAgentEnable_Click()
If (optAgentEnable.Value) Then
cmbAgentSelect.Enabled = True
frameAgentDetails.Visible = True
frameTeamDetails.Visible = False
End If
End Sub
Private Sub optTeamEnable_Click()
If (optTeamEnable.Value) Then
cmbAgentSelect.Enabled = False
frameTeamDetails.Visible = True
frameAgentDetails.Visible = False
End If
End Sub
Private Sub cmbGenRptType_Change()
If (cmbGenRptType.Value = "01 Text Report") Then
frmTextReport.Visible = True
frmChartRpt.Visible = False
End If
If (cmbGenRptType.Value = "02 Chart Report") Then
frmChartRpt.Visible = True
frmTextReport.Visible = False
End If
End Sub
Private Sub cmdNext_Click()
UpdateSelectReportTabStatus
End Sub

BIN
task4/1/frmMain.frx Normal file

Binary file not shown.

BIN
task4/1/images/Alex.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Ben.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Candy.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Danny.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Eason.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Filex.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Gary.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Henry.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Irene.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/Jenny.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/professor.avif (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/professor.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/professor.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/small_professor.jpg (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/xlsx_agent_sales.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/xlsx_agent_working_performance.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/images/xlsx_product_sales.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/1/main.xlsm Normal file

Binary file not shown.

BIN
task4/Agent Sales.xlsx Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

4
task4/FORM.md Normal file
View File

@@ -0,0 +1,4 @@
要做D乜
- generate excel sheet ? (Analysis workbook_worksheet_source.xlsx)
- [] vba form (理順番個 flow )
- 如果要 generate, 咁個 file 要 save 去邊?

Binary file not shown.

View File

@@ -0,0 +1,209 @@
# MS3111 Data Analytics with Excel VBA
## Proposal
## Team Member:
- Fung Sum Yu 57158594
- Chiu Cheung Sin 56700379
- Cheung Chun Hei 57141700
- Ma Pui Man 57302260
## Background and Source data
AB Insurance Ltd is a newly established company in 2020.
In order to analyse the insurance sales situation and evaluate the agents' working performance, the company decided to record every transaction daily and update it yearly. There are 3 source workbooks with different purpose:
1. **Product sales workbook** [Product_Sales.xlsx](../src/xlsx/Product_Sales.xlsx)
Column:
- Sales No. `PRODUCT_SALES_SALES_NO_COL`
- Date `PRODUCT_SALES_DATE_COL`
- Product Category `PRODUCT_SALES_PRODUCT_CATEGORY_COL`
- Selling Unit `PRODUCT_SALES_SELLING_UNIT_COL`
- Selling Price `PRODUCT_SALES_SELLING_PRICE_COL`
It mainly records what kind of products have been sold in 2023 with the detailed date, selling unit and selling price. There is a total of 200 invoices, followed by the Sales Number.
![](./images/Picture1.png)
1. **Agent Sales workbook** [Agent_Sales.xlsx](../src/xlsx/Agent_Sales.xlsx)
Column:
- Sales No. `AGENT_SALES_SALES_NO_COL`
- Date `AGENT_SALES_DATE_COL`
- Agent Name `AGENT_SALES_AGENT_NAME_COL`
- Team `AGENT_SALES_TEAM_COL`
- Selling Price `AGENT_SALES_SELLING_PRICE_COL`
- Commision(%) `AGENT_SALES_COMMISION_PCT_COL`
Here are the company's two groups of insurance agents in 2023 sales records, a total of two groups divided into A team and B team. Each group have 5 members, and we have a total of 10 agents. They are Alex, Ben, Candy, Danny, and Eason from the A team and Filex, Gary,Henry, Irene, and Jenny from the B team. The company keep a detailed record of each transactions date, agent name, team, selling price and commission rate, respectively.
![](./images/Picture2.png)
Different commission rates for different product types:
- Life insurance (30%)
- Accident insurance (25%)
- Health insurance (20%)
- Travel insurance (35%)
- Vehicle insurance (15%)
2. **Agent working performance workbook** [Agent_Working_Performance.xlsx](../src/xlsx/Agent_Working_Performance.xlsx)
Column:
- Date `AGENT_WORKING_PERFORMANCE_DATE_COL`
- Name `AGENT_WORKING_PERFORMANCE_NAME_COL`
- Team `AGENT_WORKING_PERFORMANCE_TEAM_COL`
- No. of New Case `AGENT_WORKING_PERFORMANCE_NO_OF_NEW_CASE_COL`
- No. of Collapsed Case `AGENT_WORKING_PERFORMANCE_NO_OF_COLLAPSED_CASE_COL`
As an insurance company, in addition to finding new business opportunities, ensuring that our customers continue to purchase our old policies is also an important indicator of how well our agent is doing. Hence, this workbook records the number of new cases set up, and the number of old policed collapsed in 2023. In case to evaluate the agent working, the data record follows the date, agent name, agents team and the specific number of new and collapsed cases.
![](./images/Picture3.png)
![](./images/Picture4.png)
## Data Manipulation:
A new Excel workbook called 'Analysis Workbook' is created to store manipulated data. In the `Combined Data` worksheet, relevant data will be extracted from the three source data workbooks mentioned in the previous section, with those duplicate entries or columns removed.
Column:
- Date `ANALYSIS_WORKBOOK_COMBINED_DATA_DATE_COL`
- Sales No. `ANALYSIS_WORKBOOK_COMBINED_DATA_SALES_NO_COL`
- Month `ANALYSIS_WORKBOOK_COMBINED_DATA_MONTH_COL`
- Quater `ANALYSIS_WORKBOOK_COMBINED_DATA_QUATER_COL`
- Agent Name `ANALYSIS_WORKBOOK_COMBINED_DATA_AGENT_NAME_COL`
- Team `ANALYSIS_WORKBOOK_COMBINED_DATA_TEAM_COL`
- Product Category `ANALYSIS_WORKBOOK_COMBINED_DATA_PRODUCT_CATEGORY_COL`
- Selling Price `ANALYSIS_WORKBOOK_COMBINED_DATA_SELLING_PRICE_COL`
- Commision(%) `ANALYSIS_WORKBOOK_COMBINED_DATA_COMMISION_PCT_COL`
- Selling Unit `ANALYSIS_WORKBOOK_COMBINED_DATA_SELLING_UNIT_COL`
- Commision($) `ANALYSIS_WORKBOOK_COMBINED_DATA_COMMISION_HKD_COL`
- Rank `ANALYSIS_WORKBOOK_COMBINED_DATA_RANK_COL`
- Bonus `ANALYSIS_WORKBOOK_COMBINED_DATA_BONUS_COL`
- Total commission `ANALYSIS_WORKBOOK_COMBINED_DATA_TOTAL_COMMISSION_COL`
- No. of Collapsed case `ANALYSIS_WORKBOOK_COMBINED_DATA_NO_OF_COLLAPSED_CASE_COL`
- Margin `ANALYSIS_WORKBOOK_COMBINED_DATA_MARGIN_COL`
![](./images/Picture5.png)
For further analysis, some columns are newly expended and computed.
### Drill down to Month and Quarter
The 'Month'(`ANALYSIS_WORKBOOK_COMBINED_DATA_MONTH_COL`) and 'Quarter'(`ANALYSIS_WORKBOOK_COMBINED_DATA_QUATER_COL`) columns display the month and quarter of the insurance transaction, respectively, according to the data in the 'Date'(`ANALYSIS_WORKBOOK_COMBINED_DATA_DATE_COL`) column.
![](./images/Picture6.png)
### Calculate every comission
As a different commission rate is assigned to each product category, a column named 'Commission($)'(`ANALYSIS_WORKBOOK_COMBINED_DATA_COMMISION_PCT_COL`) is computed to show how much the representing agent could gain from the transaction. The amount is calculated by multiplying the selling price, selling unit, and the commission rate, referred to as `=H2*J2*I2` in Excel.
![](./images/Picture7.png)
### Sum up each sales agent insurance sales per month
Each sales agent is assigned a monthly sales performance ranking by summing up each sales agent's calculated insurance sales per month (more details are provided in the next section). The ' Rank ' column shows each month's top 3 sales agents. The top 3 sales agents will receive bonuses of 1,000, 500, and 100, respectively, displayed in the "Bonus" column.
![](./images/Picture8.png)
### Calculate `total comission`
The 'Total commission' column is the sum of the sales commission and the bonus added. In Excel, `=K2+M2`.
![](./images/Picture9.png)
### Calculate `margin`
The 'Margin' column shows the overall margin of each transaction, computed by subtracting the total commission from the selling price. In Excel, =H2-N2.
![](./images/Picture10.png)
## Analysis Workbook & Report Workbook:
### 1. Sales Analysis (Monthly and Quarterly) worksheet
`SALES_ANALYSIS_MONTHLY_AND_QUARTERLY_SHEET`
![](./images/Picture11.png)
There are different columns for different datasets. Month and Quarter columns represent the timeslot of the sales. The product category column represents the types of insurance sold on the period of time. We have used the “sum if” function in excel to generate the selling unit for the total number of every month. The selling unit times the selling price of the product will equal the column of Monthly sales. We used the “sum” function in excel to generate a Quarterly sales column by adding up the data of Monthly sales for every four months. Moreover, the “commission” column of the workbook has used the “sum if” function to generate the data from the Combine Data worksheet. The Quarterly Commission columns are produced by using the “sum” function of Excel to add up the commission for every four months. Finally, we have the column of monthly margin and quarterly margin respectively. It calculates the difference between monthly sales and the commission and minus the fixed cost $1600.
The Sales Analysis (Monthly and Quarterly) contains crucial data pertaining to the sales performance of insurance products over specific time periods. The Month and Quarter columns provide a breakdown of sales figures on a monthly and quarterly basis, allowing for detailed analysis of sales trends and patterns. The Product Category column categorizes the different types of insurance products sold, offering insights into the demand and popularity of each category. The utilization of the "sum if" function in Excel to calculate selling units and monthly sales enables a comprehensive overview of the volume and revenue generated from each product category.
Moreover, the Commission column in the workbook reflects the commissions earned by sales representatives for selling insurance products, drawing data from the Combine Data Worksheet to ensure accuracy and consistency. This commission data is aggregated into the Quarterly Commission column, providing visibility into the earnings of sales personnel over a quarterly time frame.
Furthermore, the Monthly Margin and Quarterly Margin columns play a critical role in determining the profitability of the sales operations. By subtracting the total commission and fixed costs from the monthly and quarterly sales figures, these metrics offer valuable insights into the financial performance and efficiency of the sales activities. The comprehensive data presented in this workbook serves as a valuable tool for assessing sales performance, identifying opportunities for growth, and making informed business decisions.
Figures 1 (a) and 1(b) in the Report Workbook present a visual representation of the monthly sales and commissions for the year 2023. The line graphs in both figures exhibit a strikingly similar pattern, suggesting a direct relationship between sales and commissions. This correlation indicates that as sales increase or decrease, there is a corresponding impact on the commission earned by sales representatives. The alignment in the shape of the sales and commission lines signifies a consistent and proportional change between these two variables over the course of the year.
This direct variation relationship between sales and commissions has significant implications for the financial performance of the business. The interplay between these two critical metrics not only influences revenue generation but also affects the overall profitability and margin of the company. Figure 3 further illustrates the impact of this relationship on the monthly margin, which is calculated as the difference between sales, commission, and the fixed cost of $1600.
The observed fluctuations in the monthly margin can be attributed to the dynamic nature of sales and commission figures. Changes in sales volume, commission rates, or operating expenses can directly influence the monthly margin, shaping the financial health and viability of the business. These fluctuations may provide valuable insights into the efficiency of sales operations, the effectiveness of commission structures, and the overall cost management strategies employed by the company.
Based on the direct variation relationship between sales and commissions showcased in Figures 1 and 2, one hypothesis could suggest that a strategic increase in sales efforts could lead to a corresponding rise in commission earnings, contributing to improved profitability. Conversely, a decline in sales performance may result in lower commission income, potentially leading to tighter profit margins. These findings underscore the intricate interplay between sales, commissions, and margins in shaping the financial performance of the business.
| Figure 1(a) | Figure 1(b) |
| --------------------------- | --------------------------- |
| ![](./images/Picture12.png) | ![](./images/Picture13.png) |
| Figure 2: |
| --------------------------- |
| ![](./images/Picture14.png) |
| Figure 3: |
| --------------------------- |
| ![](./images/Picture15.png) |
### 2. Sales Analysis (Product Category) worksheet
![](./images/Picture16.png)
![](./images/Picture17.png)
The worksheet is to provide a comprehensive overview of sales performance for different types of insurance products on a monthly basis. By utilizing the "sum if" function in Excel, the workbook accurately calculates the sales amount and sales unit for each type of insurance, including Travel insurance, Health insurance, Life insurance, Vehicle insurance, and Accident insurance.
The Sales Amount column displays the total sales amount for each type of insurance product for a specific month, allowing for a clear comparison between different product categories. This data can be used to track sales trends, monitor performance, and identify areas for improvement in sales strategies.
Similarly, the Sales Unit column showcases the total number of cases or transactions completed for each type of insurance product within a month. This information is valuable for understanding customer demand, evaluating business growth, and making informed decisions on resource allocation.
To sum up, the Sales Analysis (Product Category) serves as a valuable tool for analyzing sales performance, identifying key trends, and making strategic decisions to drive business success in the insurance industry.
Figures 4 and 5 in Report Workbook depict the sales amount and sales unit data for a distinct month, presenting a visual representation of the distribution of sales among various types of insurance products. Through the utilization of pie charts, the data is effectively segmented to
display the relative percentages of each insurance category, enabling a straightforward comparative analysis between the different types. By visually illustrating the proportions of sales attributed to each type of insurance, stakeholders are provided with a simplified and easily interpretable overview of the sales distribution. This graphical representation facilitates a comprehensive assessment of the variations in sales performance across the diverse insurance categories, offering valuable insights into the comparative success and contribution of each product type to the overall sales volume and number of units sold. The use of pie charts in presenting the sales amount and sales unit data serves to streamline the analysis process, enabling stakeholders to swiftly discern the relative performance of different insurance categories and make well-informed decisions based on the distribution of sales in the depicted month.
| Figure 4 | Figure 5 |
| --------------------------- | --------------------------- |
| ![](./images/Picture18.png) | ![](./images/Picture19.png) |
### 3.Agent performance analysis (Commission) worksheet
![](./images/Picture20.png)
From this worksheet, we can generate charts like Figures 6 and 7 in Report Workbook which depict the total sales commission for Team A and Team B for a distinct month. Figure 8 depicts the top 5 sales agents for a distinct month. Analyzing performance helps determine whether the existing commission structure effectively incentivizes agents to achieve organizational goals. Commission analysis helps evaluate the performance of individual agents. This evaluation is crucial for providing feedback, setting performance targets, and making decisions regarding promotions or changes in responsibilities. Each bar might represent an individual agent, and the height of the bar could represent.
various performance indicators We have used the “sum if” function in Excel to generate the commission for the total number of every month and find out the top 5 agents in each month.
| Figure 6 | Figure 7 |
| --------------------------- | --------------------------- |
| ![](./images/Picture21.png) | ![](./images/Picture22.png) |
Figure 8:
![](./images/Picture23.png)
### 4.Case Persistency Worksheet
![](./images/Picture24.png)
The Case Persistency column is a new computation with equation "(No. of New Case No. of collapsed case) / (No. of New Case + No. of collapsed case)". Figure 9 and Figure 10 depict the case distribution among the new cases and collapse. Through the utilization of pie charts, the data is effectively segmented to display the relative percentages of each team.
In the context of insurance, the concepts of case distribution, new cases, collapse, and the use of bar charts for agent performance visualization can be applied in various ways to enhance efficiency, track workload, and provide insights.
| Figure 9 | Figure 10 |
| --------------------------- | --------------------------- |
| ![](./images/Picture25.png) | ![](./images/Picture26.png) |

Binary file not shown.

BIN
task4/MS3111 proposal/WINWORD_S6G9DrJu90.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture1.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture10.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture11.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture12.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture13.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture14.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture15.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture16.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture18.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture19.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture2.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture20.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture21.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture22.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture23.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture25.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
task4/MS3111 proposal/images/Picture26.png (Stored with Git LFS) Normal file

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More