Option Compare Database
Option Explicit
Public Function SQL_ABSYears() As String
Const sTableName As String = "Application"
SQL_ABSYears = "SELECT Min(StartDate) AS FirstStartDate, Max(EndDate) AS LastEndDate " _
& "FROM " & sTableName
End Function
Public Function SQL_Application() As String
SQL_Application = "Select * from Application"
End Function
Public Sub CreateTempTable()
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim tdf As DAO.TableDef
Dim sSQL As String
Const sTempTableName As String = "tempForeCast"
Dim sYears() As String
Dim sYearFlds As String
Dim iFYear As Integer
Dim iLYear As Integer
Dim iCnt As Integer
Dim sAmounts() As String
Dim sAmount As String
Set dbs = CurrentDb
'Delete temptable if exists
For Each tdf In dbs.TableDefs
If tdf.Name = sTempTableName Then dbs.TableDefs.Delete sTempTableName
Next tdf
'Fetch the absolute first date and last date
Set rs = dbs.OpenRecordset(SQL_ABSYears)
With rs
If Not .EOF And Not .BOF Then
.MoveFirst
iFYear = Year(.Fields("FirstStartDate").Value)
iLYear = Year(.Fields("LastEndDate").Value)
Else
MsgBox "No data found", vbExclamation
Exit Sub
End If
.Close
End With
'Create array holding all years between startdate and enddate
'
For iCnt = 0 To iLYear - iFYear '- 1
ReDim Preserve sYears(iCnt)
sYears(iCnt) = (iFYear + iCnt) & " Double"
Next iCnt
'Join years for create table sql
sYearFlds = Join(sYears, ", ")
sYearFlds = "ApplicationID Long, ProgramID Long, DisciplineID Long, EmployeeID Long, StartDate DateTime, EndDate DateTime, AmountApproved Double, " & sYearFlds
'create the temptable and index
sSQL = "Create Table " & sTempTableName & " (" & sYearFlds & ")"
dbs.Execute sSQL
sSQL = "CREATE UNIQUE INDEX [PrimaryKey] ON " & sTempTableName & " ([ApplicationID]) WITH PRIMARY DISALLOW NULL "
dbs.Execute sSQL
'Section to append data from Application to forecast
Set rs = dbs.OpenRecordset(SQL_Application)
With rs
.MoveFirst
Do Until .EOF
'First determine the years to forecast
sYearFlds = vbNullString
ReDim sYears(0)
ReDim sAmounts(0)
iFYear = Year(.Fields("StartDate").Value)
iLYear = Year(.Fields("EndDate").Value)
'create array for years to append
For iCnt = 0 To iLYear - iFYear '- 1
ReDim Preserve sYears(iCnt)
ReDim Preserve sAmounts(iCnt)
sYears(iCnt) = (iFYear + iCnt)
sAmounts(iCnt) = .Fields("AmountApproved").Value
Next iCnt
sYearFlds = Join(sYears, ", ")
sAmount = Join(sAmounts, ", ")
'construct the insert statment
sSQL = "Insert Into " & sTempTableName & "(ApplicationID, ProgramID, DisciplineID, EmployeeID, StartDate, EndDate, AmountApproved, " & sYearFlds & ")" _
& "Values (" & .Fields("ApplicationID").Value & ", " & .Fields("ProgramID").Value & ", " & .Fields("DisciplineID").Value & ", " & .Fields("EmployeeID").Value & ", #" & .Fields("StartDate").Value & "#, #" & .Fields("EndDate").Value & "#, " & .Fields("AmountApproved").Value & ", " & sAmount & ")"
'insert values into temptable
dbs.Execute sSQL
.MoveNext
Loop
End With
End Sub