'Imports xlData from given xl file to given access table
'Will replace any access table with given name
Public Sub ImportExcelData()
Dim t As String 'table name
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim r As Range
Dim fd As FileDialog
Dim fn As String 'filename
Dim q As Integer
Dim fns As String 'field names
Dim fdcnt As Integer 'field count
Dim dat As String 'data values
Dim sql As String
Dim i As Integer
Dim vnt As Variant
DoCmd.SetWarnings False
On Error GoTo Err_ImportExcelData
'Get data filename
Set fd = FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel Files", "*.xls"
If .Show Then
fn = .SelectedItems(1) 'File to import.
Else
Exit Sub
End If
End With
Set wb = GetObject(fn)
Set ws = wb.Sheets(1)
'Check if file contains header row
q = MsgBox("First row contains field names?", vbYesNo + vbQuestion)
'Get number of fields and field names if header row exists
fdcnt = 0
For Each r In ws.Range(ws.Range("A1"), ws.Range("A1").End(xlToRight))
If q = vbYes Then
fns = fns & "," & r
End If
fdcnt = fdcnt + 1
Next r
fns = Mid(fns, 2) 'remove preceding comma
'Create data table
t = InputBox("Enter table name to import to." & Chr(13) & _
"Note, if table already exists it will be replaced." & Chr(13) & _
"(I.e. any existing information will be deleted.)")
On Error Resume Next
DoCmd.RunSQL "DROP TABLE " & t & ""
On Error GoTo Err_ImportExcelData
sql = "CREATE TABLE " & t & " ("
If q = vbYes Then
vnt = Split(fns, ",")
For i = 0 To UBound(vnt)
vnt(i) = vnt(i) & " text"
Next i
sql = sql & Join(vnt, ",") & ")"
Else
For i = 1 To fdcnt
fns = fns & "," & "[Field" & i & "] text"
Next i
sql = sql & Mid(fns, 2) & ")"
End If
DoCmd.RunSQL sql
'Add data values
For Each r In ws.Range(ws.Range(IIf(q = vbYes, "A2", "A1")), ws.Range(IIf(q = vbYes, "A2", "A1")).End(xlDown))
dat = ""
For i = 0 To fdcnt - 1
dat = dat & ",'" & r.Offset(0, i).Value & "'"
Next i
dat = Mid(dat, 2) 'remove preceding comma
sql = "INSERT INTO " & t & " " & IIf(q = vbYes, "(" & fns & ")", "") & " VALUES (" & dat & ")"
DoCmd.RunSQL sql
Next r
Done:
If Not wb Is Nothing Then
wb.Application.DisplayAlerts = False
wb.Application.Quit
End If
Set wb = Nothing
Set ws = Nothing
Exit Sub
Err_ImportExcelData:
MsgBox Err.Description
Resume Done
End Sub
|