|
楼主 |
发表于 2017-8-21 12:59
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Private Sub Configpostcode()
Dim i As Integer, j As Integer, sht As Worksheet, para 'i,j为整数变量;sht 为excel工作表对象变量,指向某一工作表
Dim cn As Object '定义数据链接对象 ,保存连接数据库信息
Dim rs As Object '定义记录集对象,保存数据表
Set cn = CreateObject("ADODB.Connection") '创建数据链接对象
Set rs = CreateObject("ADODB.RecordSet") '创建记录集对象
'Dim cn As New ADODB.Connection '定义数据链接对象 ,保存连接数据库信息;请先添加ADO引用
'Dim rs As New ADODB.Recordset '定义记录集对象,保存数据表
Dim strCn As String, strSQL As String '字符串变量
strCn = "Provider=SQLOLEDB;Initial Catalog=" & "master" & ";User ID=" & "yue.wang" & ";Password=" & "xzy123" & ";Data Source=" & "10.234.207.32,1433" & ";Integrated Security=SSPI;Persist Security Info=True;" '定义数据库链接字符串
strSQL = "SELECT [POSTCODE] FROM [中国邮编].[dbo].[t3] where City_CH = '上海'" '定义SQL查询命令字符串
cn.Open strCn '与数据库建立连接,如果成功,返回连接对象cn
rs.Open strSQL, cn '执行strSQL所含的SQL命令,结果保存在rs记录集对象中
Dim MAB As String
MAB = Empty
Do While Not rs.EOF
'MAB = MAB & rs("POSTCODE").Value
MAB = MAB & rs.Fields("POSTCODE")
MAB = MAB & ","
rs.MoveNext
Loop
Sheets("字符串").Range("A1") = MAB
rs.Close '关闭记录集,至此,程序将把某数据表的字段1和字段2保存在excel工作表sheet1的第1、2列,行数等于数据表的记录数
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub |
|