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
原文:http://www.cnblogs.com/exayong/p/7406073.html