我对以下vba代码有点问题:
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "EXCEL-PC\EXCELDEVELOPER" ' Enter your server name here
Database_Name = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer] WHERE CountryID = 1" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
我有以下Vba代码,我想从数组中的给定值运行查询。例如,用户将以下值输入到" A"列1 2 3 4 5 6在另一个之后,之后我想将结果插入到另一个之下。例如,我在第一次查询运行时获得了26个结果,而第二个在第二次查询之后第二次给了我50需要有76行。 抱歉我的英语不好。
我还发现以下代码帮助我将所有值都放入数组中:https://social.msdn.microsoft.com/Forums/en-US/f5e97f3d-9857-469f-8255-18aa20512ba4/reading-a-range-into-vba-array?forum=isvvba
答案 0 :(得分:1)
您可以Join()
数组(从数组转换为由某个字符分隔的字符串)到您的SQL语句中
SQLStr = "SELECT * FROM [SalesLT].[Customer] WHERE CountryID IN (" & Join(YourArray, ",") & ") ORDER BY countryID;"
我们使用IN
条件为WHERE子句和ORDER BY CountryID
提供countryid列表,以便按顺序将它们加载到工作表中。