用VBA语言调用sql数据库数据到excel中

2024-12-21 19:05:47
推荐回答(1个)
回答1:

VBE 工具 引用,选中 Microsoft ActiveX Data Object 2.8 Library
我不清楚是不是UFDATA_013_2008表的VENDOR列的数据,如果不是,你自己改一下SQL语句吧,sql = "select VENDOR from UFDATA_013_2008"

Sub SQL数据导入()

Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim str As String
Dim sql As String
Dim i As Integer

str = "Provider=SQLOLEDB;Data Source=SQLSERVER服务器名或IP;DATABASE=数据库;UID=用户名;PWD=密码"
cn.Open str
Set rs = New ADODB.Recordset
sql = "select VENDOR from UFDATA_013_2008"
rs.Open sql, cn, adOpenStatic, adLockOptimistic

If Not rs.EOF Then
For i = 1 To rs.RecordCount
Sheet2.Cells(i, 1).Value = rs.Fields(0).Value
Next i
rs.MoveNext
End If
rs.Close
cn.Close
End Sub