kadgmt

Untitled

Aug 6th, 2024
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VisualBasic 31.89 KB | Source Code | 0 0
  1. Private Sub Workbook_Open()
  2.     Call InitializeWorkbook
  3.     Call InitDV_Click
  4. End Sub
  5. Option Explicit
  6. Private Sub Worksheet_Change(ByVal Target As Range) 'FilteredData worksheet change
  7.    If Not Intersect(Target, Range("A2:D2")) Is Nothing Then
  8.         Application.EnableEvents = False
  9.         If Target.Address = "$A$2" Then
  10.             Call UpdateEndDateValidation
  11.         ElseIf Target.Address = "$C$2" Then
  12.             Call UpdateEndTimeValidation
  13.         ElseIf Target.Address = "$B$2" Then
  14.             'Debug.Print "EndDate Changed"
  15.            Call FindDatesBetweenStartAndEndDates
  16.         End If
  17.         Application.EnableEvents = True
  18.     End If
  19. End Sub
  20. Option Explicit
  21. Private Sub Worksheet_Change(ByVal Target As Range)
  22.     If Not Intersect(Target, Range("A2:D2")) Is Nothing Then
  23.         Application.EnableEvents = False
  24.         If Target.Address = "$A$2" Then
  25.             Call UpdateEndDateValidation
  26.         ElseIf Target.Address = "$C$2" Then
  27.             Call UpdateEndTimeValidation
  28.         ElseIf Target.Address = "$B$2" Then
  29.             'Debug.Print "EndDate Changed"
  30.            Call FindDatesBetweenStartAndEndDates
  31.         End If
  32.         Application.EnableEvents = True
  33.     End If
  34. End Sub
  35. Option Explicit
  36. Public gMaxGlucoseY As Long
  37. Public gUniqueDates As Variant
  38. Sub FindMaxGlucoseY()
  39.     Dim ws As Worksheet
  40.     Dim lastRow As Long
  41.     Dim maxGlucose As Long
  42.     On Error GoTo ErrHandler
  43.     Set ws = ThisWorkbook.Worksheets("OrigData")
  44.     lastRow = ws.Cells(ws.Rows.count, "B").End(xlUp).Row
  45.     maxGlucose = Application.WorksheetFunction.Max(ws.Range("B2:B" & lastRow))
  46.     gMaxGlucoseY = Application.WorksheetFunction.Ceiling(maxGlucose, 20)
  47.     Exit Sub
  48. ErrHandler:
  49.     MsgBox "Error in FindMaxGlucoseY: " & Err.Description & vbNewLine & "Error Number: " & Err.Number
  50. End Sub
  51. Sub PlotGlucoseAndAvgGlucoseClick()
  52.     Dim ws As Worksheet
  53.     Dim startDate As Date, endDate As Date
  54.     Dim startTime As Date, endTime As Date
  55.     Dim uniqueDates As Variant
  56.     Set ws = ActiveSheet
  57.     startDate = ws.Range("A2").Value
  58.     endDate = ws.Range("B2").Value
  59.     startTime = ws.Range("C2").Value
  60.     endTime = ws.Range("D2").Value
  61.     If endTime = TimeSerial(0, 0, 0) Then
  62.         endTime = TimeSerial(23, 59, 59)
  63.     End If
  64.     uniqueDates = gUniqueDates
  65.     PlotMultiSeriesGlucoseVsTimeXYChart startDate, endDate, startTime, endTime, uniqueDates
  66.     PlotMultiSeriesAverageGlucoseByHourChart startDate, endDate, startTime, endTime, uniqueDates
  67.     DisplayStatsForSelectedTimeFrame startDate, endDate, startTime, endTime, uniqueDates
  68. End Sub
  69. Function GetGlucoseValuesArrayForADateRange(startDate As Date, endDate As Date, startTime As Date, endTime As Date) As Variant
  70.     Dim ws As Worksheet
  71.     Dim lastRow As Long
  72.     Dim startRow As Long, endRow As Long
  73.     Dim glucoseValues() As Integer
  74.     Dim i As Long, j As Long
  75.     On Error GoTo ErrHandler
  76.     Set ws = ThisWorkbook.Worksheets("OrigData")
  77.     lastRow = ws.Cells(ws.Rows.count, "A").End(xlUp).Row
  78.     If lastRow <= 1 Then
  79.         Err.Raise 999, , "No data found in worksheet 'OrigData'."
  80.     End If
  81.     startRow = 2
  82.     Do While startRow <= lastRow
  83.         If ws.Cells(startRow, "A").Value >= startDate + timeValue(startTime) Then
  84.             Exit Do
  85.         End If
  86.         startRow = startRow + 1
  87.     Loop
  88.     endRow = startRow
  89.     Do While endRow <= lastRow
  90.         If ws.Cells(endRow, "A").Value > endDate + timeValue(endTime) Then
  91.             Exit Do
  92.         End If
  93.         endRow = endRow + 1
  94.     Loop
  95.     If startRow >= endRow Then
  96.         Err.Raise 999, , "No data found for the specified criteria. Start Date: " & Format(startDate, "mm/dd/yyyy") & ", Start Time: " & Format(startTime, "h:mm AM/PM")
  97.     End If
  98.     ReDim glucoseValues(1 To endRow - startRow)
  99.     For i = startRow To endRow - 1
  100.         j = i - startRow + 1
  101.         glucoseValues(j) = CInt(ws.Cells(i, "B").Value)
  102.     Next i
  103.     GetGlucoseValuesArrayForADateRange = glucoseValues
  104.     Exit Function
  105. ErrHandler:
  106.     MsgBox "Error in GetGlucoseValuesArrayForADateRange: " & Err.Description & vbNewLine & "Error Number: " & Err.Number
  107.     GetGlucoseValuesArrayForADateRange = Array()  ' Return an empty array in case of error
  108. End Function
  109. Function GetTimeValuesArrayForDateRange(startDate As Date, endDate As Date, startTime As Date, endTime As Date) As Variant
  110.     On Error GoTo ErrHandler
  111.     Dim ws As Worksheet
  112.     Dim lastRow As Long
  113.     Dim startRow As Long, endRow As Long
  114.     Dim timeValues() As Double
  115.     Dim i As Long, j As Long
  116.     Set ws = ThisWorkbook.Worksheets("OrigData")
  117.     lastRow = ws.Cells(ws.Rows.count, "A").End(xlUp).Row
  118.     If lastRow <= 1 Then
  119.         Err.Raise 999, , "No data found in worksheet 'OrigData'."
  120.     End If
  121.     startRow = 2
  122.     Do While startRow <= lastRow
  123.         If ws.Cells(startRow, "A").Value >= startDate + timeValue(startTime) Then
  124.             Exit Do
  125.         End If
  126.         startRow = startRow + 1
  127.     Loop
  128.     endRow = startRow
  129.     Do While endRow <= lastRow
  130.         If ws.Cells(endRow, "A").Value > endDate + timeValue(endTime) Then
  131.             Exit Do
  132.         End If
  133.         endRow = endRow + 1
  134.     Loop
  135.     If startRow >= endRow Then
  136.         Err.Raise 999, , "No data found for the specified criteria. Start Date: " & Format(startDate, "mm/dd/yyyy") & ", Start Time: " & Format(startTime, "h:mm AM/PM")
  137.     End If
  138.     ReDim timeValues(1 To endRow - startRow)
  139.     For i = startRow To endRow - 1
  140.         j = i - startRow + 1
  141.         timeValues(j) = timeValue(ws.Cells(i, "A").Value)
  142.     Next i
  143.     GetTimeValuesArrayForDateRange = timeValues
  144.     Exit Function
  145. ErrHandler:
  146.     MsgBox "Error in GetTimeValuesArrayForDateRange: " & Err.Description & vbNewLine & "Error Number: " & Err.Number
  147.     GetTimeValuesArrayForDateRange = Array()      ' Return an empty array in case of error
  148. End Function
  149. Option Explicit
  150. Sub PlotMultiSeriesGlucoseVsTimeXYChart(startDate As Date, endDate As Date, startTime As Date, endTime As Date, uniqueDates As Variant)
  151.     Dim currentDate As Date
  152.     Dim ws As Worksheet
  153.     Dim cht As ChartObject
  154.     Dim srs As series
  155.     Dim chartLeft As Double, chartTop As Double, chartWidth As Double, chartHeight As Double
  156.     Dim chartTitle As String
  157.     Dim i As Long
  158.     Dim tempGlucoseArray As Variant
  159.     Dim tempTimeArray As Variant
  160.     Dim colorIndex As Long
  161.     Dim visibleRange As Range
  162.     Dim yValues As Variant
  163.     Dim yMax As Double
  164.     Set ws = ActiveSheet
  165.     For Each cht In ws.ChartObjects
  166.         If cht.Name = "ChartGlucose" Then
  167.             cht.Delete
  168.         End If
  169.     Next cht
  170.     Set visibleRange = ActiveWindow.ActivePane.visibleRange
  171.     chartWidth = visibleRange.Width / 2 - 6
  172.     chartHeight = visibleRange.Height - ws.Cells(3, 1).Top - 10
  173.     chartLeft = ws.Cells(3, 1).Left
  174.     chartTop = ws.Cells(3, 1).Top
  175.     Set cht = ws.ChartObjects.Add(Left:=chartLeft, Top:=chartTop, Width:=chartWidth, Height:=chartHeight)
  176.     cht.Name = "ChartGlucose"
  177.     cht.Chart.ChartType = xlXYScatterSmoothNoMarkers
  178.     Do While cht.Chart.SeriesCollection.count > 0
  179.         cht.Chart.SeriesCollection(1).Delete
  180.     Loop
  181.     colorIndex = 1
  182.     For i = LBound(uniqueDates) To UBound(uniqueDates)
  183.         currentDate = uniqueDates(i)
  184.         If currentDate >= startDate And currentDate <= endDate Then
  185.             tempGlucoseArray = GetGlucoseValuesArrayForADateRange(currentDate, currentDate, startTime, endTime)
  186.             tempTimeArray = GetTimeValuesArrayForDateRange(currentDate, currentDate, startTime, endTime)
  187.             If IsArray(tempGlucoseArray) And IsArray(tempTimeArray) And UBound(tempGlucoseArray) >= 0 And UBound(tempTimeArray) >= 0 Then
  188.                 Set srs = cht.Chart.SeriesCollection.NewSeries
  189.                 With srs
  190.                     .xValues = tempTimeArray
  191.                     .Values = tempGlucoseArray
  192.                     .Name = ""                    ' This removes the legend entry
  193.                    .Format.Line.Weight = 1       ' Adjust line weight for better visibility
  194.                    .Format.Line.Visible = True
  195.                     .Format.Line.ForeColor.RGB = RGB(colorIndex * 25 Mod 255, colorIndex * 50 Mod 255, colorIndex * 75 Mod 255)
  196.                 End With
  197.                 colorIndex = colorIndex + 1
  198.             End If
  199.         End If
  200.     Next i
  201.     yMax = gMaxGlucoseY
  202.     yValues = Array(70, 140, 180, yMax)
  203.     For i = LBound(yValues) To UBound(yValues)
  204.         Set srs = cht.Chart.SeriesCollection.NewSeries
  205.         With srs
  206.             .ChartType = xlXYScatterLines
  207.             .xValues = Array(0, 1)                ' X-values spanning the entire width of the chart
  208.            .Values = Array(yValues(i), yValues(i))
  209.             .Name = ""                            ' This removes the legend entry
  210.            .Format.Line.Weight = 1.5             ' Adjust line weight for better visibility
  211.            If yValues(i) = 70 Or yValues(i) = 140 Then
  212.                 .Format.Line.ForeColor.RGB = RGB(0, 255, 0) ' Green color for lines at 70 and 140
  213.            Else
  214.                 .Format.Line.ForeColor.RGB = RGB(255, 0, 0) ' Red color for lines at 180 and y-max
  215.            End If
  216.             .MarkerStyle = xlMarkerStyleNone      ' No markers
  217.        End With
  218.     Next i
  219.     With cht.Chart.Axes(xlCategory)
  220.         .MinimumScale = 0
  221.         .MaximumScale = 1.04166667                ' Changed as requested
  222.        .MajorUnit = 0.04166667                   ' 1 hour interval
  223.        .MinorUnit = 0.04166667                   ' 1 hour interval
  224.        .HasMajorGridlines = True
  225.         .HasMinorGridlines = True
  226.         .TickLabels.Orientation = xlUpward        ' Rotate text 270 degrees
  227.        .TickLabels.NumberFormat = "h AM/PM"
  228.     End With
  229.     With cht.Chart.Axes(xlValue)
  230.         .MajorUnit = 20
  231.         .MinorUnit = 10
  232.         .HasMajorGridlines = True
  233.         .HasMinorGridlines = True
  234.         .MinimumScale = 0
  235.         .MaximumScale = gMaxGlucoseY              ' Set max Y-axis bound to gMaxGlucoseY
  236.    End With
  237.     If startDate = endDate Then
  238.         chartTitle = "Glucose Values on " & Format(startDate, "ddd, mmm d, yyyy")
  239.     Else
  240.         chartTitle = "Glucose Values from " & Format(startDate, "mm/dd/yyyy") & " to " & Format(endDate, "mm/dd/yyyy")
  241.     End If
  242.     With cht.Chart
  243.         .HasTitle = True
  244.         .chartTitle.Text = chartTitle
  245.         .chartTitle.Format.TextFrame2.TextRange.Font.Size = 16 ' Set font size to 16
  246.        .Axes(xlCategory).HasTitle = True
  247.         .Axes(xlCategory).AxisTitle.Text = "Time"
  248.         .Axes(xlValue).HasTitle = True
  249.         .Axes(xlValue).AxisTitle.Text = "Glucose"
  250.         .HasLegend = False                        ' Remove the legend
  251.    End With
  252.     cht.Chart.Refresh
  253. End Sub
  254. Sub PlotMultiSeriesAverageGlucoseByHourChart(startDate As Date, endDate As Date, startTime As Date, endTime As Date, uniqueDates As Variant)
  255.     Dim ws As Worksheet
  256.     Dim cht As ChartObject
  257.     Dim srs As series
  258.     Dim chartLeft As Double, chartTop As Double, chartWidth As Double, chartHeight As Double
  259.     Dim chartTitle As String
  260.     Dim hourlyTotals(0 To 23) As Long
  261.     Dim hourCounts(0 To 23) As Long
  262.     Dim hourlyAverages(0 To 23) As Long
  263.     Dim i As Long, j As Long, k As Long, hourIndex As Long
  264.     Dim currentDate As Date
  265.     Dim glucoseValues As Variant
  266.     Dim timeValues As Variant
  267.     Dim xValues(0 To 23) As String
  268.     Dim totalSum As Long
  269.     Dim totalCount As Long
  270.     Dim avgGlucose As Long
  271.     Dim visibleRange As Range
  272.     Dim startHour As Integer, endHour As Integer
  273.     Dim gmi As Double
  274.     On Error GoTo ErrHandler
  275.     Set ws = ActiveSheet
  276.     For i = 0 To 23
  277.         hourlyTotals(i) = 0
  278.         hourCounts(i) = 0
  279.         xValues(i) = Format(TimeSerial(i, 0, 0), "h AM/PM")
  280.     Next i
  281.     For i = LBound(uniqueDates) To UBound(uniqueDates)
  282.         currentDate = uniqueDates(i)
  283.         If currentDate >= startDate And currentDate <= endDate Then
  284.             glucoseValues = GetGlucoseValuesArrayForADateRange(currentDate, currentDate, startTime, endTime)
  285.             timeValues = GetTimeValuesArrayForDateRange(currentDate, currentDate, startTime, endTime)
  286.             If IsArray(glucoseValues) And IsArray(timeValues) Then
  287.                 For j = LBound(glucoseValues) To UBound(glucoseValues)
  288.                     hourIndex = hour(CDate(timeValues(j)))
  289.                     hourlyTotals(hourIndex) = hourlyTotals(hourIndex) + glucoseValues(j)
  290.                     hourCounts(hourIndex) = hourCounts(hourIndex) + 1
  291.                     totalSum = totalSum + glucoseValues(j)
  292.                     totalCount = totalCount + 1
  293.                 Next j
  294.             End If
  295.         End If
  296.     Next i
  297.     For i = 0 To 23
  298.         If hourCounts(i) > 0 Then
  299.             hourlyAverages(i) = CLng(hourlyTotals(i) / hourCounts(i))
  300.         Else
  301.             hourlyAverages(i) = 0
  302.         End If
  303.     Next i
  304.     If totalCount > 0 Then
  305.         avgGlucose = CLng(totalSum / totalCount)
  306.     Else
  307.         avgGlucose = 0
  308.     End If
  309.     gmi = 3.31 + 0.02392 * avgGlucose
  310.     For Each cht In ws.ChartObjects
  311.         If cht.Name = "ChartAvgGlucose" Then cht.Delete
  312.     Next cht
  313.     Set visibleRange = ActiveWindow.ActivePane.visibleRange
  314.     chartWidth = visibleRange.Width / 2 - 6
  315.     chartHeight = visibleRange.Height - ws.Cells(3, 1).Top - 10
  316.     chartLeft = ws.Cells(3, 1).Left + chartWidth
  317.     chartTop = ws.Cells(3, 1).Top
  318.     Set cht = ws.ChartObjects.Add(Left:=chartLeft, Top:=chartTop, Width:=chartWidth, Height:=chartHeight)
  319.     cht.Chart.ChartType = xlColumnClustered
  320.     cht.Name = "ChartAvgGlucose"
  321.     Set srs = cht.Chart.SeriesCollection.NewSeries
  322.     With srs
  323.         .Values = hourlyAverages
  324.         .xValues = xValues
  325.         .Name = ""
  326.     End With
  327.     For i = 1 To srs.Points.count
  328.         With srs.Points(i).Format.Fill.ForeColor
  329.             If srs.Values(i) <= 97 Then
  330.                 .RGB = RGB(0, 255, 0)             ' Green for values 96 or less
  331.            ElseIf srs.Values(i) >= 132 Then
  332.                 .RGB = RGB(255, 0, 0)             ' Red for values 132 or more
  333.            ElseIf srs.Values(i) >= 98 Then
  334.                 .RGB = RGB(255, 165, 0)           ' Orange for values between 97 and 131
  335.            End If
  336.         End With
  337.     Next i
  338.     With cht.Chart.Axes(xlCategory)
  339.         .TickLabelSpacing = 1
  340.         .TickMarkSpacing = 1
  341.         .HasMajorGridlines = True
  342.         .TickLabels.Orientation = xlUpward
  343.         .TickLabels.NumberFormat = "h AM/PM"
  344.     End With
  345.     With cht.Chart.Axes(xlValue)
  346.         .MajorUnit = 20
  347.         .MinorUnit = 10
  348.         .HasMajorGridlines = True
  349.         .HasMinorGridlines = True
  350.         .MinimumScale = 0
  351.         .MaximumScale = gMaxGlucoseY              ' Set max Y-axis bound to gMaxGlucoseY
  352.    End With
  353.     If startDate = endDate Then
  354.         chartTitle = "Average Hourly Glucose on " & Format(startDate, "ddd, mmm d, yyyy") & " from " & Format(startTime, "h AM/PM") & " to " & Format(endTime, "h AM/PM")
  355.     Else
  356.         chartTitle = "Average Hourly Glucose from " & Format(startDate, "mm/dd/yyyy") & " " & Format(startTime, "h:mm AM/PM") & _
  357.                      " to " & Format(endDate, "mm/dd/yyyy") & " " & Format(endTime, "h:mm AM/PM")
  358.     End If
  359.     With cht.Chart
  360.         .HasTitle = True
  361.         .chartTitle.Text = chartTitle
  362.         .chartTitle.Format.TextFrame2.TextRange.Font.Size = 16 ' Set font size to 16
  363.        .Axes(xlCategory).HasTitle = True
  364.         .Axes(xlCategory).AxisTitle.Text = "Hour"
  365.         .Axes(xlValue).HasTitle = True
  366.         .Axes(xlValue).AxisTitle.Text = "Average Glucose"
  367.         .HasLegend = False
  368.     End With
  369.     srs.HasDataLabels = True
  370.     With srs.DataLabels
  371.         .ShowValue = True
  372.         .Position = xlLabelPositionInsideEnd
  373.         .NumberFormat = "0"
  374.     End With
  375.     Dim lineSeriesNames As Variant
  376.     Dim lineValues As Variant
  377.     Dim lineColors As Variant
  378.     Dim lineSrs As series
  379.     Dim lineText As Variant
  380.     lineSeriesNames = Array("97Normal", "132Diabetic", "AverageGlucose")
  381.     lineValues = Array(97, 132, avgGlucose)
  382.     lineColors = Array(RGB(0, 255, 0), RGB(255, 0, 0), RGB(0, 0, 0))
  383.     For k = 0 To 2
  384.         Set lineSrs = cht.Chart.SeriesCollection.NewSeries
  385.         With lineSrs
  386.             .ChartType = xlXYScatterLines
  387.             .xValues = Array(0, 24)               ' X-values spanning the entire width of the chart
  388.            .Values = Array(lineValues(k), lineValues(k))
  389.             .Name = lineSeriesNames(k)
  390.             .Format.Line.ForeColor.RGB = lineColors(k)
  391.             If k = 0 Then
  392.                 .Format.Line.Weight = 3           ' Normal line width 3
  393.            Else
  394.                 .Format.Line.Weight = 1.5         ' Other lines width 2
  395.            End If
  396.             .MarkerStyle = xlMarkerStyleNone      ' No markers
  397.        End With
  398.     Next k
  399.     Dim textBox As Shape
  400.     Set textBox = cht.Chart.Shapes.AddTextbox(msoTextOrientationHorizontal, 50, 50, 300, 100)
  401.     With textBox.TextFrame2.TextRange
  402.         .Text = "Average Glucose: " & avgGlucose & " (" & Format(gmi, "0.0") & "%)" & vbCrLf & "<= 97 (5.6%) Normal" & vbCrLf & ">= 98 (5.7%) & <= 132 (6.5%) (132) Pre-Diabetic" & vbCrLf & ">= 132 (6.5%) Diabetic"
  403.         .Font.Size = 14
  404.         .Font.Bold = msoTrue
  405.         .ParagraphFormat.Alignment = msoAlignRight
  406.         .Paragraphs(1).Font.Fill.ForeColor.RGB = RGB(0, 0, 0) ' Black for Average
  407.        .Paragraphs(2).Font.Fill.ForeColor.RGB = RGB(0, 255, 0) ' Green for Normal
  408.        .Paragraphs(3).Font.Fill.ForeColor.RGB = RGB(255, 165, 0) ' Orange for Pre Diabetic
  409.        .Paragraphs(4).Font.Fill.ForeColor.RGB = RGB(255, 0, 0) ' Red for Diabetic
  410.    End With
  411.     cht.Chart.Refresh
  412.     Exit Sub
  413. ErrHandler:
  414.     MsgBox "Error in PlotMultiSeriesAverageGlucoseByHourChart: " & Err.Description & vbNewLine & "Error Number: " & Err.Number
  415. End Sub
  416. Option Explicit
  417. Sub DisplayStatsForSelectedTimeFrame(startDate As Date, endDate As Date, startTime As Date, endTime As Date, uniqueDates As Variant)
  418.     Dim ws As Worksheet
  419.     Dim glucoseValues As Variant
  420.     Dim timeValues As Variant
  421.     Dim allGlucoseValues() As Double
  422.     Dim currentDate As Date
  423.     Dim i As Long, j As Long, k As Long
  424.     Dim dataCount As Long
  425.     Dim gmi As Double
  426.     Set ws = ActiveSheet
  427.     ReDim allGlucoseValues(1 To 1)
  428.     dataCount = 0
  429.     For i = LBound(uniqueDates) To UBound(uniqueDates)
  430.         currentDate = uniqueDates(i)
  431.         If currentDate >= startDate And currentDate <= endDate Then
  432.             glucoseValues = GetGlucoseValuesArrayForADateRange(currentDate, currentDate, startTime, endTime)
  433.             timeValues = GetTimeValuesArrayForDateRange(currentDate, currentDate, startTime, endTime)
  434.             If IsArray(glucoseValues) And IsArray(timeValues) Then
  435.                 For j = LBound(glucoseValues) To UBound(glucoseValues)
  436.                     dataCount = dataCount + 1
  437.                     ReDim Preserve allGlucoseValues(1 To dataCount)
  438.                     allGlucoseValues(dataCount) = glucoseValues(j)
  439.                 Next j
  440.             End If
  441.         End If
  442.     Next i
  443.     If dataCount > 0 Then
  444.         Dim statsRange As Range
  445.         Set statsRange = ws.Range("J1")
  446.         ' Headers
  447.        statsRange.Offset(0, 0).Value = "Count"
  448.         statsRange.Offset(0, 1).Value = "Min"
  449.         statsRange.Offset(0, 2).Value = "Avg"
  450.         statsRange.Offset(0, 3).Value = "Median"
  451.         statsRange.Offset(0, 4).Value = "Max"
  452.         statsRange.Offset(0, 5).Value = "Std. Dev"
  453.         statsRange.Offset(0, 6).Value = "GMI%"
  454.         Dim avgGlucose As Long
  455.         avgGlucose = Application.WorksheetFunction.Average(allGlucoseValues)
  456.         gmi = 3.31 + 0.02392 * avgGlucose
  457.         ' Values
  458.        statsRange.Offset(1, 0).Value = dataCount
  459.         statsRange.Offset(1, 1).Value = Int(Application.WorksheetFunction.Min(allGlucoseValues))
  460.         statsRange.Offset(1, 2).Value = Int(avgGlucose)
  461.         statsRange.Offset(1, 3).Value = Int(Application.WorksheetFunction.Median(allGlucoseValues))
  462.         statsRange.Offset(1, 4).Value = Int(Application.WorksheetFunction.Max(allGlucoseValues))
  463.         statsRange.Offset(1, 5).Value = Application.WorksheetFunction.StDev_P(allGlucoseValues)
  464.         statsRange.Offset(1, 6).Value = gmi
  465.         ' Format cells
  466.        With statsRange.Offset(1, 0).Resize(1, 5)
  467.             .NumberFormat = "0"
  468.             .Font.Bold = True
  469.         End With
  470.         statsRange.Offset(1, 5).NumberFormat = "0.00"
  471.         statsRange.Offset(1, 5).Font.Bold = True
  472.         statsRange.Offset(1, 6).NumberFormat = "0.0"
  473.         statsRange.Offset(1, 6).Font.Bold = True
  474.         ' Add border
  475.        With statsRange.Resize(2, 7)
  476.             .Borders.Weight = xlThin
  477.             .Borders(xlEdgeBottom).Weight = xlMedium
  478.         End With
  479.     Else
  480.         MsgBox "No data found for the specified date and time range.", vbInformation
  481.     End If
  482. End Sub
  483. Option Explicit
  484. Sub PrevButtonClick()
  485.     Dim ws As Worksheet
  486.     Dim currentStartDate As Date
  487.     Dim newStartDate As Date
  488.     Dim startTime As Date, endTime As Date
  489.     Dim uniqueDates As Variant
  490.     Set ws = ActiveSheet
  491.     currentStartDate = ws.Range("A2").Value
  492.     startTime = ws.Range("C2").Value
  493.     endTime = ws.Range("D2").Value
  494.     If endTime = TimeSerial(0, 0, 0) Then
  495.         endTime = TimeSerial(23, 59, 59)
  496.     End If
  497.     Debug.Print "PrevButtonClick calling GetUniqueDates"
  498.     uniqueDates = gUniqueDates
  499.     newStartDate = FindPreviousDate(currentStartDate, uniqueDates)
  500.     If newStartDate <> 0 Then
  501.         ws.Range("A2").Value = newStartDate
  502.         'ws.Range("B2").Value = newStartDate ' Set end date same as start date
  503.        PlotMultiSeriesGlucoseVsTimeXYChart newStartDate, newStartDate, startTime, endTime, uniqueDates
  504.         PlotMultiSeriesAverageGlucoseByHourChart newStartDate, newStartDate, startTime, endTime, uniqueDates
  505.         DisplayStatsForSelectedTimeFrame newStartDate, newStartDate, startTime, endTime, uniqueDates
  506.     Else
  507.         MsgBox "No previous date available."
  508.     End If
  509. End Sub
  510. Sub NextButtonClick()
  511.     Dim ws As Worksheet
  512.     Dim currentStartDate As Date
  513.     Dim newStartDate As Date
  514.     Dim startTime As Date, endTime As Date
  515.     Dim uniqueDates As Variant
  516.     Set ws = ActiveSheet
  517.     currentStartDate = ws.Range("A2").Value
  518.     startTime = ws.Range("C2").Value
  519.     endTime = ws.Range("D2").Value
  520.     If endTime = TimeSerial(0, 0, 0) Then
  521.         endTime = TimeSerial(23, 59, 59)
  522.     End If
  523.     uniqueDates = gUniqueDates
  524.     newStartDate = FindNextDate(currentStartDate, uniqueDates)
  525.     If newStartDate <> 0 Then
  526.         ws.Range("A2").Value = newStartDate
  527.         'ws.Range("B2").Value = newStartDate ' Set end date same as start date
  528.        PlotMultiSeriesGlucoseVsTimeXYChart newStartDate, newStartDate, startTime, endTime, uniqueDates
  529.         PlotMultiSeriesAverageGlucoseByHourChart newStartDate, newStartDate, startTime, endTime, uniqueDates
  530.         DisplayStatsForSelectedTimeFrame newStartDate, newStartDate, startTime, endTime, uniqueDates
  531.     Else
  532.         MsgBox "No next date available."
  533.     End If
  534. End Sub
  535. Function FindPreviousDate(currentDate As Date, uniqueDates As Variant) As Date
  536.     Dim i As Long
  537.     For i = UBound(uniqueDates) To LBound(uniqueDates) Step -1
  538.         If uniqueDates(i) < currentDate Then
  539.             FindPreviousDate = uniqueDates(i)
  540.             Exit Function
  541.         End If
  542.     Next i
  543.     FindPreviousDate = 0                          ' Return 0 if no previous date found
  544. End Function
  545. Function FindNextDate(currentDate As Date, uniqueDates As Variant) As Date
  546.     Dim i As Long
  547.     For i = LBound(uniqueDates) To UBound(uniqueDates)
  548.         If uniqueDates(i) > currentDate Then
  549.             FindNextDate = uniqueDates(i)
  550.             Exit Function
  551.         End If
  552.     Next i
  553.     FindNextDate = 0                              ' Return 0 if no next date found
  554. End Function
  555. Sub CreateHeatMap()
  556.     Dim wsHeatMap As Worksheet
  557.     Dim wsOrigData As Worksheet
  558.     Dim uniqueDates As Variant
  559.     Dim uniqueMonths As Collection
  560.     Dim currentDate As Date
  561.     Dim avgGlucose As Double
  562.     Dim glucoseValues As Variant
  563.     Dim totalGlucose As Double
  564.     Dim count As Long
  565.     Dim i As Long, j As Long, k As Long
  566.     Dim dayOfMonth As Integer
  567.     Dim targetCell As Range
  568.     Dim monthCell As Range
  569.     Dim monthYear As String
  570.     Dim lastRow As Long
  571.     On Error GoTo ErrHandler
  572.     Set wsHeatMap = ThisWorkbook.Worksheets("heatmap")
  573.     Set wsOrigData = ThisWorkbook.Worksheets("OrigData")
  574.     wsHeatMap.Cells.Clear
  575.     wsHeatMap.Cells.ClearFormats
  576.     uniqueDates = gUniqueDates
  577.     Set uniqueMonths = New Collection
  578.     On Error Resume Next
  579.     For i = LBound(uniqueDates) To UBound(uniqueDates)
  580.         monthYear = Format(uniqueDates(i), "MMM-YY")
  581.         uniqueMonths.Add monthYear, monthYear
  582.     Next i
  583.     On Error GoTo 0
  584.     wsHeatMap.Cells(3, 2).Value = "Month"
  585.     For i = 1 To 31
  586.         wsHeatMap.Cells(3, i + 2).Value = i
  587.     Next i
  588.     wsHeatMap.Rows(3).Font.Bold = True
  589.     wsHeatMap.Rows(3).Font.Size = 12
  590.     wsHeatMap.Columns(2).Font.Bold = True
  591.     wsHeatMap.Columns(2).Font.Size = 12
  592.     For i = 1 To uniqueMonths.count
  593.         monthYear = uniqueMonths(i)
  594.         Set monthCell = wsHeatMap.Cells(i + 3, 2) ' Month column is column B
  595.        monthCell.Value = monthYear
  596.         monthCell.NumberFormat = "MMM-YY"         ' Format the cell as "MMM-YY"
  597.        ' Loop through unique dates to find matching month/year
  598.        For j = LBound(uniqueDates) To UBound(uniqueDates)
  599.             If Format(uniqueDates(j), "MMM-YY") = monthYear Then
  600.                 currentDate = uniqueDates(j)
  601.                 glucoseValues = GetGlucoseValuesArrayForADateRange(currentDate, currentDate, TimeSerial(0, 0, 0), TimeSerial(23, 59, 59))
  602.                 ' Calculate average glucose for the date
  603.                If IsArray(glucoseValues) Then
  604.                     totalGlucose = 0
  605.                     count = 0
  606.                     For k = LBound(glucoseValues) To UBound(glucoseValues)
  607.                         totalGlucose = totalGlucose + glucoseValues(k)
  608.                         count = count + 1
  609.                     Next k
  610.                     If count > 0 Then
  611.                         avgGlucose = Int(totalGlucose / count) ' Convert to integer
  612.                    Else
  613.                         avgGlucose = 0
  614.                     End If
  615.                 Else
  616.                     avgGlucose = 0
  617.                 End If
  618.                 ' Determine the day of the month and target cell
  619.                dayOfMonth = Day(currentDate)
  620.                 Set targetCell = wsHeatMap.Cells(i + 3, dayOfMonth + 2) ' Offset by 3 rows and 2 columns
  621.                ' Write average glucose value in the target cell
  622.                targetCell.Value = avgGlucose
  623.                 ' Apply conditional formatting
  624.                If avgGlucose <= 97 Then
  625.                     targetCell.Interior.Color = RGB(0, 255, 0) ' Green
  626.                ElseIf avgGlucose >= 98 And avgGlucose <= 132 Then
  627.                     targetCell.Interior.Color = RGB(255, 165, 0) ' Orange
  628.                ElseIf avgGlucose >= 132 Then
  629.                     targetCell.Interior.Color = RGB(255, 0, 0) ' Red
  630.                End If
  631.             End If
  632.         Next j
  633.     Next i
  634.     lastRow = wsHeatMap.Cells(wsHeatMap.Rows.count, "B").End(xlUp).Row
  635.     With wsHeatMap.Range("B3:AG" & lastRow)
  636.         .Borders(xlEdgeLeft).LineStyle = xlContinuous
  637.         .Borders(xlEdgeTop).LineStyle = xlContinuous
  638.         .Borders(xlEdgeBottom).LineStyle = xlContinuous
  639.         .Borders(xlEdgeRight).LineStyle = xlContinuous
  640.         .Borders(xlInsideVertical).LineStyle = xlContinuous
  641.         .Borders(xlInsideHorizontal).LineStyle = xlContinuous
  642.     End With
  643.     wsHeatMap.Range("B3:AG" & lastRow).Columns.AutoFit
  644.     Exit Sub
  645. ErrHandler:
  646.     MsgBox "Error in CreateHeatMap: " & Err.Description & vbNewLine & "Error Number: " & Err.Number
  647. End Sub
  648. Sub CreateHeatMapMSCoPilot()
  649.     Dim wsHeatMap As Worksheet
  650.     Dim wsOrigData As Worksheet
  651.     Dim uniqueDates As Variant
  652.     Dim uniqueMonths As Collection
  653.     Dim currentDate As Date
  654.     Dim avgGlucose As Double
  655.     Dim glucoseValues As Variant
  656.     Dim totalGlucose As Double
  657.     Dim count As Long
  658.     Dim i As Long, j As Long, k As Long
  659.     Dim dayOfMonth As Integer
  660.     Dim targetCell As Range
  661.     Dim monthCell As Range
  662.     Dim monthYear As String
  663.     Dim lastRow As Long
  664.     On Error GoTo ErrHandler
  665.     Application.ScreenUpdating = False
  666.     Application.Calculation = xlCalculationManual
  667.     Set wsHeatMap = ThisWorkbook.Worksheets("heatmap")
  668.     Set wsOrigData = ThisWorkbook.Worksheets("OrigData")
  669.     wsHeatMap.Cells.Clear
  670.     wsHeatMap.Cells.ClearFormats
  671.     uniqueDates = gUniqueDates
  672.     Set uniqueMonths = New Collection
  673.     On Error Resume Next
  674.     For i = LBound(uniqueDates) To UBound(uniqueDates)
  675.         monthYear = Format(uniqueDates(i), "MMM-YY")
  676.         uniqueMonths.Add monthYear, monthYear
  677.     Next i
  678.     On Error GoTo 0
  679.     wsHeatMap.Cells(3, 2).Value = "Month"
  680.     For i = 1 To 31
  681.         wsHeatMap.Cells(3, i + 2).Value = i
  682.     Next i
  683.     wsHeatMap.Rows(3).Font.Bold = True
  684.     wsHeatMap.Rows(3).Font.Size = 12
  685.     wsHeatMap.Columns(2).Font.Bold = True
  686.     wsHeatMap.Columns(2).Font.Size = 12
  687.     For i = 1 To uniqueMonths.count
  688.         monthYear = uniqueMonths(i)
  689.         Set monthCell = wsHeatMap.Cells(i + 3, 2) ' Month column is column B
  690.        monthCell.Value = monthYear
  691.         monthCell.NumberFormat = "MMM-YY"         ' Format the cell as "MMM-YY"
  692.        ' Loop through unique dates to find matching month/year
  693.        For j = LBound(uniqueDates) To UBound(uniqueDates)
  694.             If Format(uniqueDates(j), "MMM-YY") = monthYear Then
  695.                 currentDate = uniqueDates(j)
  696.                 glucoseValues = GetGlucoseValuesArrayForADateRange(currentDate, currentDate, TimeSerial(0, 0, 0), TimeSerial(23, 59, 59))
  697.                 ' Calculate average glucose for the date
  698.                If IsArray(glucoseValues) Then
  699.                     totalGlucose = 0
  700.                     count = 0
  701.                     For k = LBound(glucoseValues) To UBound(glucoseValues)
  702.                         totalGlucose = totalGlucose + glucoseValues(k)
  703.                         count = count + 1
  704.                     Next k
  705.                     If count > 0 Then
  706.                         avgGlucose = Int(totalGlucose / count) ' Convert to integer
  707.                    Else
  708.                         avgGlucose = 0
  709.                     End If
  710.                 Else
  711.                     avgGlucose = 0
  712.                 End If
  713.                 ' Determine the day of the month and target cell
  714.                dayOfMonth = Day(currentDate)
  715.                 Set targetCell = wsHeatMap.Cells(i + 3, dayOfMonth + 2) ' Offset by 3 rows and 2 columns
  716.                ' Write average glucose value in the target cell
  717.                targetCell.Value = avgGlucose
  718.                 ' Apply conditional formatting
  719.                If avgGlucose <= 97 Then
  720.                     targetCell.Interior.Color = RGB(0, 255, 0) ' Green
  721.                ElseIf avgGlucose >= 98 And avgGlucose <= 132 Then
  722.                     targetCell.Interior.Color = RGB(255, 165, 0) ' Orange
  723.                ElseIf avgGlucose >= 132 Then
  724.                     targetCell.Interior.Color = RGB(255, 0, 0) ' Red
  725.                End If
  726.             End If
  727.         Next j
  728.     Next i
  729.     lastRow = wsHeatMap.Cells(wsHeatMap.Rows.count, "B").End(xlUp).Row
  730.     With wsHeatMap.Range("B3:AG" & lastRow)
  731.         .Borders(xlEdgeLeft).LineStyle = xlContinuous
  732.         .Borders(xlEdgeTop).LineStyle = xlContinuous
  733.         .Borders(xlEdgeBottom).LineStyle = xlContinuous
  734.         .Borders(xlEdgeRight).LineStyle = xlContinuous
  735.         .Borders(xlInsideVertical).LineStyle = xlContinuous
  736.         .Borders(xlInsideHorizontal).LineStyle = xlContinuous
  737.     End With
  738.     wsHeatMap.Range("B3:AG" & lastRow).Columns.AutoFit
  739.     Application.ScreenUpdating = True
  740.     Application.Calculation = xlCalculationAutomatic
  741.     Exit Sub
  742. ErrHandler:
  743.     MsgBox "Error in CreateHeatMap: " & Err.Description & vbNewLine & "Error Number: " & Err.Number
  744.     Application.ScreenUpdating = True
  745.     Application.Calculation = xlCalculationAutomatic
  746. End Sub
Advertisement
Add Comment
Please, Sign In to add comment