我正在尝试在Excel中使用VBA来查询SQL数据库,我得到了以下代码作为起点很棒,但我不知道编写连接字符串的语法到目前为止一直无法找到它。希望你们能帮助我。
Dim cn as new ADODB.Connection
Dim rs as new ADODB.Recordset
Cn.ConnectionString = “your connection string”
Cn.Open
Rs.Open “query like SELECT * FROM MYTABLE etc.”, cn
Range(“A1”).CopyFromRecordset rs
Rs.close
Cn.close
答案 0 :(得分:1)
这段代码可以帮助你(这只是我手边的东西,接近你想要做的事情而不是你的重写),但你的连接字符串会因你的数据库而异。转到here以获取有关字符串本身语法的更多信息。您收到编译错误,因为您没有正确的引用。在VBE中,转到“工具”并选择“参考”。确保选中ActiveX Data Objects 6.1库。
Private Sub GetFieldNames()
Set con1 = New ADODB.Connection
Set rs1 = New ADODB.Recordset
Dim ProjectName As String
Dim ConCat As String
con1.ConnectionString = "Provider=SQLOLEDB;Data Source=SERVERADDRESS;Initial Catalog=DATABSE;IntegratedSecurity=SSPI"
con1.Open
With rs1
.ActiveConnection = con1
.Open "SELECT column_name,* From information_schema.columns Where table_name = 'Projects' ORDER by ordinal_position"
Sheet1.Range("A1").CopyFromRecordset rs1
.Close
End With
con1.Close
Set con1 = Nothing
End Sub