使用Excel VBA将多个值插入连接查询

我有一个工作Excel电子表格,它使用VBA来更改连接查询中的参数,具体取决于input到单个单元格中的内容。 它不能使用Excel参数来获取值,因为variables位于连接中,而不在查询的where部分。 所以我知道这在原则上起作用,至less对于一个数据单元来说。

我现在需要创build一个新的电子表格,我需要将一系列数据放入查询中。

查询看起来像这样:

select* FROM TABLE_A其中ID('A','B','C')

VBA从电子表格的一列中选取值A,B和C,目前看起来像这样:

Dim ID_Range As Range Sheets("Data").Select Set ID_Range = Sheets("Data").Range("A1:A10") With ActiveWorkbook.Connections("Query from Database_A").ODBCConnection .BackgroundQuery = True .CommandText = Array( _ "Select * FROM Table_A A WHERE A.ID in " "(" + ID_Range + ")") .CommandType = xlCmdSql .Connection = Array(Array( _ ODBC;Description= **** .RefreshOnFileOpen = False .SavePassword = False .SourceConnectionFile = "" .SourceDataFile = "" .ServerCredentialsMethod = xlCredentialsMethodIntegrated .AlwaysUseConnectionFile = False End With 

我希望在删除公司的具体信息时不会删除任何重要的代码。
当它运行时,会出现错误:下标超出范围

我需要做些什么才能使这个工作?

如果你没有ODBCConnection对象的具体需求(而且在你的情况下我没有看到它的优势),你可以简单地使用ADODB甚至是老的DAO来做到这一点!

 ' Create a recordset object.Dim rsPubs As ADODB.Recordset Set rsPubs = New ADODB.Recordset With rsPubs ' Assign the Connection object. .ActiveConnection = cnPubs ' Extract the required records. .Open "SELECT * FROM Authors" ' Copy the records into cell A1 on Sheet1. Sheet1.Range("A1").CopyFromRecordset rsPubs ' Tidy up .Close End With cnPubs.Close Set rsPubs = Nothing Set cnPubs = Nothing 

(从https://support.microsoft.com/fr-fr/help/306125/how-to-import-data-from-microsoft-sql-server-into-microsoft-excel粘贴的代码示例)

最好的办法是创build一个函数来处理范围

 Function getCommaSeparatedList(Source As Range) As String Dim cell As Range Dim results As String For Each cell In Source results = results & "'" & cell.Value & "'," Next getCommaSeparatedList = Left(results, Len(results) - 1) End Function 

像这样尝试。

 Dim ID_Range As Range Dim vR() As String Dim n As Integer Dim strRange As String Sheets("Data").Select Set ID_Range = Sheets("Data").Range("A1:A10") For Each Rng In ID_Range n = n + 1 ReDim Preserve vR(1 To n) vR(n) = "'" & Rng & "'" Next Rng strRange = Join(vR, ",") With ActiveWorkbook.Connections("Query from Database_A").ODBCConnection .BackgroundQuery = True .CommandText = Array("Select * FROM Table_A A WHERE A.ID in (" & strRange & ")")