|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
以实现先删除表中原有数据,已WID作为关键字,随后再插入数据。
下来要实现的就是可以在对话框中输入关键字,而不是要在代码中直接填写。因为每隔一段时间就要使用新的关键字了。还有就是数据库的用户名和密码也是要更换的。- Sub qqqQQQ1()
- Dim conn As New ADODB.Connection
- Dim conn2
- 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=.;uid=sa;pwd=dz;database=mainlogsql_cq;"
- Set wkSheet = Worksheets("sheet2")
- '删除表中原有数据,已成功
- strTemp = "DELETE FROM JP_JXSJB WHERE WID='H38'"
- conn.Execute strTemp
- RowNum = Range("c65536").End(xlUp).Row
- On Error GoTo 9
- conn.BeginTrans
- K = 0
- For i = 2 To RowNum
- If wkSheet.Cells(i, 1).Value <> 0 Then
- '拼写INSERT语句的SQL语句
- strTemp = "insert into JP_JXSJB(WID,SKNO,RID,DATE,TIME,ACTC,JXLX,XH,DEPTH,XDD,XDF,FWD,FWF,VDEPTH,X,Y,ZWY,ZFW,QJBHL,CLSJ,BZ) "
- strTemp = strTemp & " values( '" & wkSheet.Cells(i, 1).Value & "' , '" & _
- wkSheet.Cells(i, 2).Value & "' , '" & _
- wkSheet.Cells(i, 3).Value & "' , '" & _
- wkSheet.Cells(i, 4).Value & "' , '" & _
- wkSheet.Cells(i, 5).Value & "' , '" & _
- wkSheet.Cells(i, 6).Value & "' , '" & _
- wkSheet.Cells(i, 7).Value & "' , '" & _
- wkSheet.Cells(i, 8).Value & "' , '" & _
- wkSheet.Cells(i, 9).Value & "' , '" & _
- wkSheet.Cells(i, 10).Value & "' , '" & _
- wkSheet.Cells(i, 11).Value & "' , '" & _
- wkSheet.Cells(i, 12).Value & "' , '" & _
- wkSheet.Cells(i, 13).Value & "' , '" & _
- wkSheet.Cells(i, 14).Value & "' , '" & _
- wkSheet.Cells(i, 15).Value & "' , '" & _
- wkSheet.Cells(i, 16).Value & "' , '" & _
- wkSheet.Cells(i, 17).Value & "' , '" & _
- wkSheet.Cells(i, 18).Value & "' , '" & _
- wkSheet.Cells(i, 19).Value & "' , '" & _
- wkSheet.Cells(i, 20).Value & "' , '" & _
- wkSheet.Cells(i, 21).Value & "')"
- '执行INSERT语句
- conn.Execute strTemp
- K = K + 1
- End If
- Next
- conn.CommitTrans '结束插入操作的事务
- 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
复制代码 还是要谢谢各位的帮忙啊。对excel的控件还不是很熟悉,继续钻研中。因为不是学编程的,只能看懂,所以都是在前人的基础上直接修改代码。呵呵。希望大家不要吐槽 |
|