如何创build一个返回可变大小数组的excel函数

我想创build一个Excel函数,返回一个SQL查询的结果。 如果结果大小为1×1,我可以这样做。 但是,如果结果比这更大,我不能使代码工作。 有没有解决scheme? 我特别努力的事实是,在我发现的所有例子中,需要select正确数量的单元格,而我的sql查询的结果可以是任何大小…并且随时间变化。

这是我迄今使用的:

Public Function getTS(field As String) As String Set oConnection = New ADODB.Connection Dim oRecordset As ADOR.Recordset oConnection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=AISDB;Data Source=mydomainlocation\mydatabase;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;" Set oRecordset = oConnection.Execute("select " & field & " from mytable where country = 'China'") If oRecordset.EOF Then getTS = "n/a" Else getTS = oRecordset(field) End If End Function 

啊 – 对不起,我以为你正在写函数返回一个vba子程序的值。 如果你想要一个UDF,你将不得不返回一个变体数组,并在电子表格中input一个数组公式作为数组公式。 这意味着你将不得不知道有多less行将被提前返回。

  Public Function getTS(fieldnames As String) As variant Set oConnection = New ADODB.Connection Dim oRecordset As ADOR.Recordset oConnection.Open.... Set oRecordset = .... Dim x as long dim y as long y = 1 redim A(rs.fields.count,1) do while not rs.eof For x = 1 to rs.fields.count A(x,y)=rs(x) Next x Rs.movenext y = y+1 Redim preserve A(rs.fields.count,y+1) Loop rs.close GetTS = A() End Function 

返回logging集本身

 Public Function getTS(field As String) As Recordset Set oConnection = New ADODB.Connection Dim oRecordset As ADOR.Recordset oConnection.Open.... Set oRecordset = .... Set GetTS = oRecordset End Function 

然后通过仅指定左上angular的单元格将结果放入单元格中

  Activesheet.range("a2").CopyFromRecordset GetTS("myField")