簡體   English   中英

VBA從功能返回結構類型

[英]VBA return struct Type from Function

我使用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函數嗎?

謝謝你的幫助

你需要這樣的東西

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

代替

dim myCar as SqlReturnMyCar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM