Excel 使用单元格的值 查询MySQL数据库并返回数据给相应的单元格
Dim MyConn As Object
Private Sub ConnectDB()
Set MyConn = CreateObject("ADODB.Connection") ----->创建连接对象
Dim str As String
str = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _ ---->拼接连接语句 odbc驱动
"SERVER=localhost;" & _ ----> 主机
"PORT=3306;" & _ ----->端口号
"DATABASE=test;" & _ ----->指定数据库
"USER=read;" & _ ------>用户名
"PASSWORD=read;" & _ ------>密码
"Option=3"
MyConn.Open str ---->打开连接
Dim sql As String
Dim i As Integer
Dim field As String
-----------循环开始
For i=1 To 500
field = Worksheets("Sheet4").Cells(i, 5) --->从单元格获取查询条件
sql = "select delivery_no from tb_table where tb_table.order_id = '" & field &"'" ----->拼接sql
Sheets("sheet1").Cells(i, 3).CopyFromRecordset MyConn.Execute(sql) ----->把查询结果赋值到sheet1第3列
Next i
-------------循环结束
MyConn.Close ----->关闭连接
End Sub
posted on 2017-08-21 18:43 robert_hly 阅读(462) 评论(0) 编辑 收藏 举报