|
楼主 |
发表于 2004-3-12 15:51
|
显示全部楼层
做了注释的简化程序:
Sub insertData() Dim Conn As New ADODB.Connection Dim Rs As New ADODB.Recordset Dim I%, strTemp$, strTemp2$, RowNum% Dim wkSheet As Worksheet I = MsgBox("确认要导入数据吗?", vbYesNo) If I = 7 Then Exit Sub End If '建立与SQL的连接 Conn.Open "provider=sqloledb.1;persist security info=false;user id=用户名;pwd=口令;data source=192.168.2.2;initial catalog=首选数据库"
Application.ScreenUpdating = False Set wkSheet = Worksheets("Check") wkSheet.Activate '找出不为空的需要倒入SQL的数据 RowNum = Range("a1").End(xlUp).Row
'开始倒数据
'直接插入数据表 Conn.BeginTrans '开始一个事务,防止别人同时操作同一个表 For I = 2 To RowNum If wkSheet.Cells(I, 4).Value <> "" Then '拼写INSERT语句的SQL语句 strTemp = "insert into tclass (name,code) " strTemp = strTemp & " vaues('" & wkSheet.Cells(I, 1).Value & ",'" & wkSheet.Cells(I, 2).Value & "')" '执行INSERT语句 Conn.Execute strTemp End If Next Conn.CommitTrans '结束插入操作的事务 ThisWorkbook.Save '显示需要替换的记录条数 Rs.Open "select count(*) from tclass where tclass.sdate is null", Conn, adOpenKeyset MsgBox "需要替换的记录条数:" & Str(Rs.RecordCount) Rs.Close '将表中的日期字段填上 Conn.Execute "update tclass set tclass.sdate=" & Format(Date, "yyyy-mm-dd") & " where tclass.sdate is null" Conn.Close '关闭链接 Set Rs = Nothing '释放内存 Set Conn = Nothing '释放内存 Set wkSheet = Nothing Application.ScreenUpdating = True MsgBox "导入完毕!" End Sub
|
|