VBA从函数

时间:2018-04-03 13:49:51

标签: vba excel-vba struct excel

我使用EXCEL VBA: 我做一个SQL查询(SELECT * FROM CARS)

这是我的SQL函数:

Public Type SqlReturnMyCar
 Name As String
 Color As String
 Vmax As Integer
 Price As Double
End Type

Public Function SqlQueryTest(Query As String) As SqlReturnMyCar

 'open connection
   cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DbSource

 'set recordSet
   Set rs = cn.Execute(Query)
   i = 0
'recordset to Excel sheet
   Do While Not rs.EOF


    Dim myCar As SqlReturnMyCar
    myCar(i).Name = rs.Fields("NAME")
    myCar(i).Color = rs.Fields("COLOR")
    myCar(i).Vmax = rs.Fields("VMAX")
    myCar(i).Price = rs.Fields("PRICE")

     i = i + 1
     rs.MoveNext
       Loop

    'close connection
       cn.Close

    'return values
        Set SqlQueryTest = myCar
        Set myCar = Nothing

    End Function

查询在另一个没有类型结构的函数中工作。 我收到错误:需要对象问题出在哪里以及如何以正确的方式查看SQL函数? 也许我有另外一辆带有以下结构的桌子卡车:

Public Type SqlReturnMyTruck
 Name As String
 Color As String
 Vmax As Integer
 Price As Double
 Size as Double
 Weight as Double
End Type

如果我发送查询(SELECT * FROM TRUCKS) 现在桌子还有2个柱子? 我需要另一个SQL函数吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

你需要这样的东西

dim myCar() as SqlReturnMyCar redim myCar(rs.Recordcount)

而不是

dim myCar as SqlReturnMyCar