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

时间:2017-11-14 10:54:32

标签: sql arrays excel excel-vba excel-formula vba

我正在尝试创建一个返回sql查询结果的excel函数。 如果结果大小为1x1,我可以这样做。但是,如果结果大于那个,我无法使代码工作。有解决方案吗?我特别挣扎的是,在我发现的所有示例中,都需要选择正确数量的单元格,而我的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

2 个答案:

答案 0 :(得分:1)

啊 - 对不起,我以为你正在写函数将值返回给vba子程序。如果您需要UDF,则必须返回变量数组,并在电子表格中将其作为数组公式输入相应数量的单元格。这意味着您必须事先知道将返回多少行。

 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

答案 1 :(得分:0)

返回记录集本身

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

然后通过使用

仅指定左上角的单元格将结果放入单元格中
  Activesheet.range("a2").CopyFromRecordset GetTS("myField")