是否可以将 SQL 查询(用 Excel VBA 编写)的输出直接放入逗号分隔的字符串变量中,而不是像下面的代码一样将其添加到工作表中,然后将其添加到数组中? 我只需要直接在逗号分隔变量中添加 SQL 输出(id)并绕过工作表。 ID 都是数字,最多可以有 50K
Const sqlconnection = "Provider=sqloledb;"
conn.ConnectionString = sqlconnection
conn.Open
Dim arrData As Variant
Dim rs As Recordset, output As String
Dim v As String
v = "SELECT id FROM table"
Set rs = conn.Execute(v)
With wb.ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
.Refresh
End With
arrData = wb.ActiveSheet.Range("A2").CurrentRegion.Columns(1).Value
Set Dic = CreateObject("Scripting.Dictionary")
For idx = 2 To UBound(arrData, 1)
If arrData(idx, 1) <> "" Then
Dic(arrData(idx, 1)) = ""
End If
Next idx
output = Join(Dic.Keys, ",")
Debug.Print output
GetRows
,可以将记录集中的所有数据读取到二维数组中(请注意,即使只读取一列,结果也是二维的)。您唯一需要知道的是,第一个维度是字段索引,第二个维度是行号,我发现这总是有点违反直觉。两个维度都是从 0 开始的。
不幸的是,
Join
命令不适用于二维数组,因此您需要手动创建一个一维数组。当然,您也可以像在代码中一样使用字典。
v = "SELECT id FROM table"
Set rs = conn.Execute(v)
' Read all the data into 2-dimensional array
Dim mydata
mydata = rs.GetRows
' Create a 1-dimensional array
Dim i As Long
ReDim a(LBound(mydata, 2) To UBound(mydata, 2))
For i = LBound(mydata, 2) To UBound(mydata, 2)
a(i) = mydata(0, i)
Next
Dim output As String
output = Join(a, ",")
Debug.Print output