subasatran > 10-10-18, 06:07 PM
ongke0711 > 11-10-18, 02:53 PM
Private Sub cmdImport_Click()
Dim sFilePath As String
sFilePath = Me.txtFilePath
ImportDataFromRange sFilePath, Me.OpenArgs
MsgBox "Completed import."
DoCmd.Close acForm, "frm_SelectFileDlg"
End Sub
Function ImportDataFromRange(sFilePath As String, sImportTable As String)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim tbl As TableDef, fld As Field
Dim sSQL As String
DoCmd.Hourglass True
sSQL = "DELETE * FROM " & sImportTable
CurrentDb.Execute sSQL, dbFailOnError
'Excel variables'
Dim oExcel As Object
Dim oWkb As Object
Dim oSheet As Object
Dim oRange As Object
Dim lastRow As Long, firstrow As Integer
Dim r As Integer, c As Integer, i As Integer
Set db = CurrentDb
Set rs = db.OpenRecordset(sImportTable, dbOpenDynaset)
Set oExcel = CreateObject("Excel.Application")
Set oWkb = oExcel.Workbooks.Open(sFilePath)
Set oSheet = oWkb.Sheets("Sheet1")
lastRow = oSheet.UsedRange.Row - 1 + oSheet.UsedRange.Rows.Count
Select Case Me.OpenArgs
Case "List_Information"
Set oRange = oSheet.Range("A7:AC" & lastRow)
firstrow = 7
Case "List_Detail"
Set oRange = oSheet.Range("A4:M" & lastRow)
firstrow = 4
End Select
Debug.Print "So dong: " & oRange.Rows.Count & " | So cot: " & oRange.Columns.Count
For r = firstrow To lastRow
rs.AddNew
For c = 1 To oRange.Columns.Count
rs.Fields(c - 1) = oSheet.Cells(r, c)
Next c
rs.Update
Next r
DoCmd.Hourglass False
oExcel.Quit
Set oExcel = Nothing
rs.Close
Set rs = Nothing
End Function