|
下面是我写的一个导入,导到固定的表里面。
Dim xlsApplication As New Excel.Application
Dim xlsWorkBook As New Excel.Workbook
Dim xlsWorkSheet As New Excel.Worksheet
Dim xlsFileSearch As FileSearch
Dim strExcelFile As String
Dim lngExcelRowCount As Long
Dim lngExcelColumnCount As Long
Dim lngRowIndex As Long
Dim lngColumnIndex As Long
Dim strExcelArray(6) As String
Dim dlgOpenExcel As FileDialog
Dim cnn As New ADODB.Connection
Dim cmm As New ADODB.Command
Set cnn = CurrentProject.Connection
Set cmm.ActiveConnection = cnn
'首先判断是否符合导入条件-->新增记录,有订单单号
If IsNull(Me.月份) = True Or Me.月份 = "" Then
MsgBox "--请输入导入的月份--", vbInformation, "提示"
Exit Sub
ElseIf Me.N_房租水电作业单身.Form.Recordset.RecordCount > 0 Then
MsgBox "此单已有资料不可以再次导入!", vbInformation, "提示"
Exit Sub
End If
'打开Excel文件
Set dlgOpenExcel = Application.FileDialog(msoFileDialogOpen)
With dlgOpenExcel
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Microsoft Excel 文件", "*.xls"
.FilterIndex = 1
If .Show = -1 Then
strExcelFile = dlgOpenExcel.SelectedItems(1)
'判断所要打开的Excel文件是否存在
Set xlsFileSearch = Application.FileSearch
With xlsFileSearch
.NewSearch
.LookIn = Left(strExcelFile, InStrRev(strExcelFile, "\") - 1)
.FileName = Right(strExcelFile, Len(strExcelFile) - InStrRev(strExcelFile, "\"))
If .Execute > 0 Then '文件存在
'初始化数据源(Excel)
xlsApplication.Workbooks.Open strExcelFile
Set xlsWorkBook = xlsApplication.Workbooks(.FileName)
Set xlsWorkSheet = xlsWorkBook.Worksheets(1)
xlsWorkSheet.Activate
lngExcelRowCount = xlsWorkSheet.UsedRange.Rows.Count '记录行数
lngExcelColumnCount = xlsWorkSheet.UsedRange.Columns.Count '记录列数
If lngExcelRowCount > 1 And lngExcelColumnCount > 1 Then
SysCmd acSysCmdClearStatus
For lngRowIndex = 2 To lngExcelRowCount '第一行为表列名
For lngColumnIndex = 1 To lngExcelColumnCount
strExcelArray(lngColumnIndex) = xlsWorkSheet.Cells(lngRowIndex, lngColumnIndex).Value
Next lngColumnIndex
cmm.CommandText = "Insert [N-房租水电单身] (年度,月份,员工代号,水电,姓名,部门代号) " & _
"Values ('" & Me.年度 & "','" & Me.月份 & "','" & strExcelArray(1) & "','" & Round(strExcelArray(2), 1) & "'," & _
"'" & DLookup("姓名", "N-基本资料单头", "[员工代号]='" & strExcelArray(1) & "'") & "'," & _
"'" & DLookup("部门别", "N-基本资料单头", "[员工代号]='" & strExcelArray(1) & "'") & "')"
cmm.Execute
SysCmd acSysCmdSetStatus, "成功导入:" & lngRowIndex - 1 & " / " & lngExcelRowCount - 1
Next lngRowIndex
Me.N_房租水电作业单身.Form.Refresh
MsgBox "导入成功!", vbInformation
SysCmd acSysCmdClearStatus
Else
MsgBox "您所打开的Excel文件中,没有任何记录!", vbExclamation
End If
Else '文件不存在
MsgBox "文件不存在!" & vbCrLf & strExcelFile, vbExclamation
End If
End With
End If
End With
Err_Handler_Command29:
cnn.Close
Set cnn = Nothing
Set dlgOpenExcel = Nothing
Set xlsFileSearch = Nothing
Set xlsWorkSheet = Nothing
xlsWorkBook.Close False
Set xlsWorkBook = Nothing
xlsApplication.DisplayAlerts = False
xlsApplication.Quit
Set xlsApplication = Nothing
If Err.number <> 0 Then
MsgBox Err.Description, vbExclamation
End If |
|