Function PopulateCheckBoxArea()
If System.IO.File.Exists(TextBox1.Text) = True Then
'Clear checkbox area
CheckedListBox1.Items.Clear()
' Open excel
Dim excelapp As Excel.Application
Dim WB As Excel.Workbook
Dim WS As Excel.Worksheet
excelapp = New Excel.Application
WB = excelapp.Workbooks.Open(TextBox1.Text)
Dim CheckValid As Boolean
Dim SheetsAdded As Boolean = False
' Cycle through each sheet
For Each WS In WB.Worksheets
Try
CheckValid = True
If WS.Range("B4").Value.ToString <> "Employee Name:" Then
CheckValid = False
End If
If WS.Range("H4").Value.ToString <> "Week No.:" Then
CheckValid = False
End If
If WS.Range("F8").Value.ToString <> "Cost" Then
CheckValid = False
End If
' Check to see if the sheet has already been added to the database
If CheckValid = True Then
' Get name of employee from spreadsheet
Dim aName As Array
aName = Split(WS.Range("C4").Value, " ")
Dim nameexists = False
Dim sheetadded = False
' Check if the Employee is already in the Database
Dim currentemployeeID As Int32
Dim aEmployeeID As Int32
Using connection As New SqlConnection(ConnectionString)
Using command As New SqlCommand("SELECT NameFirst, NameLast, EmployeeID FROM Employees", _
connection)
connection.Open()
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
currentemployeeID = reader("EmployeeID")
If aName(0) = RemoveWhiteSpace(reader("NameFirst")) Then
If aName(1) = RemoveWhiteSpace(reader("NameLast")) Then
' The name exists in the database, get the EmployeeID to match the name
aEmployeeID = currentemployeeID
nameexists = True
End If
End If
End While
End Using
End Using
End Using
''''' Timesheet Table ''''''
If nameexists = True Then
Dim aWeekNumber As Int32 = WS.Range("I4").Value
Using connection As New SqlConnection(ConnectionString)
Using command As New SqlCommand("SELECT TimesheetID, EmployeeID, WeekNumber FROM Timesheet", _
connection)
connection.Open()
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
If aWeekNumber = RemoveWhiteSpace(reader("WeekNumber")) Then
If aEmployeeID = RemoveWhiteSpace(reader("EmployeeID")) Then
' The Timesheet has already been added
sheetadded = True
End If
End If
End While
End Using
End Using
End Using
End If
' Add the sheet to the list
If sheetadded = False Then
CheckedListBox1.Items.Add(WS.Name) ' Populate the checkbox area
SheetsAdded = True
End If
End If
Catch ex As NullReferenceException ' Catch errors that arrise from merged cells.
Catch ex As Exception
MsgBox(ex.ToString) ' any other errors will be caught here
End Try
Marshal.ReleaseComObject(WS)
Next
' Close Excel
WB.Close()
Marshal.ReleaseComObject(WB)
excelapp.Quit()
Marshal.ReleaseComObject(excelapp)
excelapp = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
If SheetsAdded = False Then
MsgBox("There were no valid sheets in this workbook.")
End If
Else
MsgBox("That file does not exist")
End If
End Function