You're getting close. BTW, the code you posted shouldn't compile: make
sure to include
Option Explicit
at the beginning of every code module.
With six columns in your destination table the actual SQL statements
will look like this. Note the apostrophes to delimit literal text values
such as the workbook and worksheet names:
INSERT INTO tblT
SELECT F1 AS Location,
'WWW' As WorkbookRef
'ZZZ' As WorksheetRef
DD As Day,
FXX AS Value1,
FYY AS Value2
FROM [Excel 8.0;HDR=No;database=C:\MyWorkbook.xls;].[ZZZ$]
in each case WWW will be replaced by the name of the workboook, ZZZ by
the name of the sheet, DD by the day of the month, and XX and YY by the
column numbers for that day.
The code to generate it will look like something like this (untested).
Note that you have to include spaces or linebreaks to separate the
"words":
strSQL = "INSERT INTO " & TableName & vbCrLf _
& "SELECT " & F1 & "AS Location, " & vbCrLf _
& "'" & XLwb.Name & "' AS WorkbookRef, " & vbCrLf _
& "'" & XLSheet & "' AS WorksheetRef, " & vbCrLf _
& CStr(j/2) & " AS Day, " & vbCrLf _
& "F" & CStr(j) & " As Value1, " & vbCrLf _
& "F" & CStr(j+1) & " As Value2 " & vbCrLf _
& "FROM [Excel 8.0;HDR=No;database=" & XLFile _
& ";].[" & XLSheet & "]"
I've been working on this and I think I am close, here is the code I am using:
Function ExcelImportResiduals()
Dim XLapp As Object
Dim XLFile As String
Dim XLSheet As String
Dim XLRange As String
Dim TableName As String
Dim z As Integer
Dim SheetCount As Integer
Dim XX As Integer
Dim YY As Integer
Dim TheDay As Integer
Set XLapp = GetObject(, "Excel.Application")
XLapp.Visible = True 'Excel is visible!! or if False not
visible!!
XLFile = "t:\Desktop\d\Monmouth\03.xls" 'Your File
TableName = "ResidualData" 'Table to import into
XLRange = "!" 'Specifies the area to be imported,
if you just enter
XX = j
JJ = j + 1
TheDay = j / 2
Set XLwb = XLapp.Workbooks.Open(XLFile) 'Opens your file in Excel
SheetCount = XLapp.activeworkbook.Sheets.Count 'Gives you the total
number of Sheets
For z = 1 To SheetCount
XLSheet = XLapp.activeworkbook.Sheets(z).Name 'get name of sheet
number z
XLSheet = XLSheet & XLRange 'add range to
sheetname
For j = 2 To (XLapp.activeworkbook.Sheets(z).UsedRange.Columns.Count
- 1) Step 2
strSQL = "INSERT INTO" & TableName & "SELECT " & F1 & "As
Location, F" & XX & " As Value1, F" & YY & " As Value2, " & XLSheet & " As
MYear, " & TheDay & " As Day FROM [Excel 8.0;HDR=No;database=" & XLFile &
";].[" & XLSheet & "]"
dbD.Execute strSQL, dbFailOnError
Next j
Next z
MsgBox "Imported Successfully "
XLapp.Quit
Set XLapp = Nothing
Set XLwb = Nothing
End Function
My problem (at least one of them) is in my strSQL, I am not sure how to
write that so that value1 comes from excel column j and value 2 comes from
excel column j +1
Also the format of the strSQL is probably off.
Any help?