[COLOR=Blue]Option Compare Database [/COLOR]
---------------------------------------------------------------
[COLOR=Red]'||| Make sure that the following REFERENCES are set:....
'||| MICROSOFT OFFICE 10.0 OBJECT LIBRARY
'||| MICROSOFT EXCEL 10.0 OBJECT LIBRARY[/COLOR]
---------------------------------------------------------------
[COLOR=Red]'Function to check if selected CSV file is already open[/COLOR]
Function IsFileOpen(strFullPathFileName As String) As Boolean
Dim hdlFile As Long
On Error GoTo FileIsOpen:
hdlFile = FreeFile
Open strFullPathFileName For Random Access Read Write Lock Read Write As hdlFile
IsFileOpen = False
Close hdlFile
Exit Function
FileIsOpen:
IsFileOpen = True
Close hdlFile
End Function
-------------------------------------------------------
Private Sub Command0_Click()
On Error GoTo csv_import_err
Dim objExcel As Excel.Application
Set objExcel = New Excel.Application
Dim strfilename As String
strfilename = objExcel.Application.GetOpenFilename("Select CSV file, *.csv", , "CSV files")
[COLOR=Red]'If CANCEL is clicked[/COLOR]
Select Case strfilename
Case False
GoTo end_
Case Else
GoTo CONT
End Select
CONT:
[COLOR=Red]'If selected file is open, abort program[/COLOR]
If IsFileOpen(strfilename) Then
MsgBox "The file you have selected is open. Please close this file and run program again.", vbInformation, "Program Error"
GoTo end_
End If
[COLOR=Red]'Format CSV file[/COLOR]
Set objworkbook = objExcel.Workbooks.Open(strfilename, , False)
objExcel.Columns("A:B").Insert Shift:=xlToRight
objExcel.Range("A5").FormulaR1C1 = "Account No"
objExcel.Range("B5").FormulaR1C1 = "Invoice No"
objExcel.Range("A6:A" & objExcel.Range("C65536").End(xlUp).Row).FormulaR1C1 = objExcel.Range("D1").Value
objExcel.Range("B6:B" & objExcel.Range("C65536").End(xlUp).Row).FormulaR1C1 = objExcel.Range("F1").Value
objExcel.Rows("1:4").Delete Shift:=xlUp
objExcel.Range("AE1").FormulaR1C1 = "Second Ref"
objExcel.Range("AF1").FormulaR1C1 = "Third Ref"
objExcel.Application.ActiveWorkbook.Close True
[COLOR=Red]'Import CSV file to Access table[/COLOR]
DoCmd.TransferText acImportDelim, , "tbl_invoice_dat", strfilename, True
MsgBox "CSV file..." & vbNewLine & vbNewLine & strfilename & vbNewLine & vbNewLine & "...has been imported.", vbInformation, "Import Complete"
end_:
Set objExcel = Nothing
Set objworkbook = Nothing
Exit Sub
csv_import_err:
MsgBox "The following error has occurred." & vbNewLine & vbNewLine & Err.Number & vbNewLine & Err.Description & vbNewLine & vbNewLine & "Please check the CSV file that needs importing.", vbCritical, "Program Error"
Set objExcel = Nothing
Set objworkbook = Nothing
End Sub