
Option Explicit On
Imports System.Data.SqlClient
Imports System.Globalization


Public Class frmTest

    Public Function CalendarWeek(ByVal nWeek As Integer, ByVal nYear As Integer) As Date

        ' Wochentag des 4. Januar des Jahres ermitteln
        Dim dStart As New Date(nYear, 1, 4)
        Dim nDay As Integer = (dStart.DayOfWeek + 6) Mod 7 + 1

        ' Beginn der 1. KW des Jahres
        Dim dFirst As Date = dStart.AddDays(1 - nDay)

        ' Gesuchte KW ermitteln
        Return dFirst.AddDays((nWeek - 1) * 7)
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim BRG As New cBrgDb
        
        Dim today As Date = Date.Today
        Dim dayIndex As Integer = today.DayOfWeek
        If dayIndex < DayOfWeek.Monday Then
            dayIndex += 7 'Monday is first day of week, no day of week should have a smaller index
        End If
        Dim dayDiff As Integer = dayIndex - DayOfWeek.Monday
        Dim monday As Date = today.AddDays(-dayDiff)
        Dim sunday As Date = monday.AddDays(6)
      
        Dim buergschaften As List(Of cBuergschaft) = BRG.getBrgVonBis(monday.ToShortDateString, sunday.ToShortDateString)
      
        Dim exclApp As Object 'as Application
        Dim Datei As Object 'as WorkBook
        Dim Blatt As Object 'as WorkSheet
        exclApp = CreateObject("Excel.Application")


        With exclApp
            .Visible = True
            Dim sPath As String = My.Computer.FileSystem.GetTempFileName
            My.Computer.FileSystem.WriteAllBytes(sPath, My.Resources.Bürgschaften_Vorlage, False)

            Datei = .Workbooks.Open(sPath) 'Anpassen
            Blatt = Datei.Worksheets("Auswertung") 'Anpassen
            'Blatt.Range("A1").Value = TextBox1.Text

            'Wochentage
            Dim aktdate As Date = monday
            'Dim cnt As Integer = 6
            For i As Integer = 6 To 12
                Blatt.Range("A" & i).Value = aktdate.ToString("ddd, dd.MM.yyyy")
                '  MsgBox(aktdate.ToLongTimeString)
                For Each b In buergschaften
                    If b.brg_datum = aktdate.ToShortDateString Then
                        Blatt.Range("B" & i).Value = CDec(b.brg_at_woche) ': MsgBox(b.brg_at_woche)
                        Blatt.Range("D" & i).Value = CDec(b.brg_at_tag) ': MsgBox(b.brg_at_tag)
                        Blatt.Range("F" & i).Value = CDec(b.brg_de_woche) ': MsgBox(b.brg_de_woche)
                        Blatt.Range("H" & i).Value = CDec(b.brg_de_tag) ': MsgBox(b.brg_de_tag)
                        Exit For
                    End If
                Next

                aktdate = aktdate.AddDays(1)
            Next


            'Datei.close(True)
            '.quit()
        End With
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

    End Sub
End Class

