|
如下会有结果吧
如果数据都已录入数据库了还要保存文件干吗?用时提取出来就是了
Sub qqq1()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i%, strTemp$, RowNum%, K%
Dim wkSheet As Worksheet
If MsgBox("确认要导入数据吗?", vbYesNo) = 7 Then Exit Sub
'建立与SQL的连接
conn.Open "Driver={SQL Server};server=192.168.107.111;uid=sa;pwd=sa;database=JSSY;"
Application.ScreenUpdating = False
Set wkSheet = Worksheets("原始数据")
On Error GoTo 9
conn.BeginTrans
K = 0
With wkSheet
RowNum = .Range("c65536").End(xlUp).Row
For i = 2 To RowNum
If .Cells(i, 2).Value <> 0 Then
If .Cells(i, "M").Value <> "已录入" Then
Dim SQL$
SQL = "select 编号 from 物资信息 where 编号 ='" & .Cells(i, 2).Value & "'"
Set rs = Nothing
'这里要加一句
rs.open sql,conn,1,1,1
If rs.RecordCount > 1 Then '存在旧的号的话就删除
conn.Execute "delete 物资信息 where 编号 ='" & .Cells(i, 2).Value & "'"
End If
'拼写INSERT语句的SQL语句
strTemp = "insert into 物资信息 (编号,材质楞型,楞别,班组,类别,长度,宽度,门幅,路数,订单数,入库数) "
strTemp = strTemp & " values( '" & .Cells(i, 2).Value & "' , '" & _
.Cells(i, 3).Value & "' , '" & _
.Cells(i, 4).Value & "' , '" & _
.Cells(i, 5).Value & "' , '" & _
.Cells(i, 6).Value & "' , '" & _
.Cells(i, 7).Value & "' , '" & _
.Cells(i, 8).Value & "' , '" & _
.Cells(i, 9).Value & "' , '" & _
.Cells(i, 10).Value & "' , '" & _
.Cells(i, 11).Value & "' , '" & _
.Cells(i, 12).Value & "')"
'执行INSERT语句
conn.Execute strTemp
K = K + 1
.Cells(i, "M").Value = "已录入" '防止重复比较加快录入速度
End If
End If
Next
End With
conn.CommitTrans '结束插入操作的事务
On Error GoTo 0
ThisWorkbook.Save
'显示已经插入的记录条数
conn.Close '关闭链接
Set rs = Nothing '释放内存
Set conn = Nothing '释放内存
Set wkSheet = Nothing
Application.ScreenUpdating = True
MsgBox "导入完毕!" & Chr(10) & Chr(10) & "已经插入的条数:" & K
Exit Sub
9:
conn.RollbackTrans
MsgBox Err.Description & "第" & i & "行 导入出错"
End Sub
[ 本帖最后由 sunsoncheng 于 2011-8-4 08:11 编辑 ] |
|